python爬蟲之定位網頁元素的三種方式
python爬蟲之定位網頁元素的三種方式
2018年08月02日 13:30:02 Barry__ 閱讀數:1373 標籤: python 更多
個人分類: python
版權宣告:本文為博主原創文章,轉載請註明出處 https://blog.csdn.net/rankun1/article/details/81357179
在做爬蟲的過程中,網頁元素的定位是比較重要的一環,本文總結了python爬蟲中比較常用的三種定位網頁元素的方式。
1.普通的BeautifulSoup find系列操作
2.BeautifulSoup css選擇器
3. xpath
這三種方式靈活運用,再配合上正則表示式,沒有什麼網頁能難倒你啦。
我們以獲取豆瓣電影top250第一頁的電影標題為例來比較:
import requests
from bs4 import BeautifulSoup
from lxml import etree
# 通過find定位標籤
# BeautifulSoup文件:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
def bs_parse_movies(html):
movie_list = []
soup = BeautifulSoup(html, "lxml")
# 查詢所有class屬性為hd的div標籤
div_list = soup.find_all('div', class_='hd')
# 獲取每個div中的a中的span(第一個),並獲取其文字
for each in div_list:
movie = each.a.span.text.strip()
movie_list.append(movie)
return movie_list
# css選擇器定位標籤
# 更多ccs選擇器語法:http://www.w3school.com.cn/cssref/css_selectors.asp
# 注意:BeautifulSoup並不是每個語法都支援
def bs_css_parse_movies(html):
movie_list = []
soup = BeautifulSoup(html, "lxml")
# 查詢所有class屬性為hd的div標籤下的a標籤的第一個span標籤
div_list = soup.select('div.hd > a > span:nth-of-type(1)')
# 獲取每個span的文字
for each in div_list:
movie = each.text.strip()
movie_list.append(movie)
return movie_list
# XPATH定位標籤
# 更多xpath語法:https://blog.csdn.net/gongbing798930123/article/details/78955597
def xpath_parse_movies(html):
et_html = etree.HTML(html)
# 查詢所有class屬性為hd的div標籤下的a標籤的第一個span標籤
urls = et_html.xpath("//div[@class='hd']/a/span[1]")
movie_list = []
# 獲取每個span的文字
for each in urls:
movie = each.text.strip()
movie_list.append(movie)
return movie_list
def get_movies():
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36',
'Host': 'movie.douban.com'
}
link = 'https://movie.douban.com/top250'
r = requests.get(link, headers=headers, timeout=10)
print("響應狀態碼:", r.status_code)
if 200 != r.status_code:
return None
# 三種定位元素的方式:
# 普通BeautifulSoup find
return bs_parse_movies(r.text)
# BeautifulSoup css select
return bs_css_parse_movies(r.text)
# xpath
return xpath_parse_movies(r.text)
movies = get_movies()
print(movies)