2018年08月02日 13:30:02 Barry__ 閱讀數:1373 標籤: python 更多css
我的分類: pythonhtml
版權聲明:本文爲博主原創文章,轉載請註明出處 https://blog.csdn.net/rankun1/article/details/81357179python
在作爬蟲的過程當中,網頁元素的定位是比較重要的一環,本文總結了python爬蟲中比較經常使用的三種定位網頁元素的方式。正則表達式
1.普通的BeautifulSoup find系列操做app
2.BeautifulSoup css選擇器python爬蟲
3. xpathurl
這三種方式靈活運用,再配合上正則表達式,沒有什麼網頁能難倒你啦。spa
咱們以獲取豆瓣電影top250第一頁的電影標題爲例來比較:.net
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)
ssr