14_Python_爬蟲利器Requests-HTML使用方法

  • requests-html 是基於現有的框架 PyQuery、Requests、lxml、beautifulsoup4等庫進行了二次封裝,做者將Requests設計的簡單強大的優勢帶到了該項目中。html

  • GiHub項目地址:https://github.com/kennethreitz/requests-htmlgit

1.安裝

pip install requests-html

2.教程與使用

2.1 發送get請求

from requests_html import HTMLSession

session = HTMLSession()
# 發出GET請求:
resposse = session.get('http://news.qq.com/')

2.2 按原樣獲取頁面上全部連接的列表(不包括錨點):

#按原樣獲取頁面上全部連接的列表(不包括錨點):

print(r.html.links)

#輸出內容:{'http://www.mohrss.gov.cn/', 'http://www.dahe.cn/', ......}

2.3 以絕對形式抓取頁面上全部連接的列表(錨點除外):

# 以絕對形式抓取頁面上全部連接的列表(錨點除外):

print(r.html.absolute_links)

#輸出內容:{'http://new.qq.com/omn/20180630A0L1ED.html', 'http://news.qq.com/a/20180624/001511.htm', 'http://new.qq.com/omn/20180630A12MEU.html', ......}

2.4使用CSS選擇器選擇一個元素:

# 使用CSS選擇器選擇第一個元素:
title = r.html.find('.f14>a', first=True).text
print(title)
# 輸出內容:重磅!2018年版自貿試驗區外資准入負面清單出爐

#注意:first=True的意思是獲取第一個元素,若是不加上就是獲取全部的符合的元素

2.5 attrs 獲取元素的全部屬性:

# attrs  獲取元素的全部屬性:
title = r.html.find('.f14>a', first=True)
print(title.attrs)

# 輸出內容:{'target': '_blank', 'class': ('linkto',), 'href': 'http://new.qq.com/omn/FIN2018063001805300'}

2.6 獲取元素的html:

#   獲取元素的html:
title = r.html.find('.f14>a', first=True)
print(title.html)

# 輸出內容:<a target="_blank" class="linkto" href="http://new.qq.com/omn/FIN2018063001805300">重磅!2018年版自貿試驗區外資准入負面清單出爐</a>&#13;

2.7 搜索元素內的連接:

#   搜索元素內的連接:
title = r.html.find('.f14>a', first=True)
print(title.absolute_links)

# 輸出內容:{'http://new.qq.com/omn/FIN2018063001805300'}

2.8 在頁面上搜索文字:

#   在頁面上搜索文字:
title = r.html.search('重磅!{}年版自貿試驗區外資准入負面清單出爐')[0]
print(title)

# 輸出內容:2018

2.9 XPath路徑定位元素

#   XPath路徑定位元素
title = r.html.xpath('//div[@class="text"]/em/a/text()')[0]
print(title)

# 輸出內容:重磅!2018年版自貿試驗區外資准入負面清單出爐

2.10 解析本地文件

from requests_html import HTML

doc = """<a href='http://news.qq.com/'>"""

html = HTML(html=doc)
print(html.links)

# 輸出內容:{'http://news.qq.com/'}

3.騰訊新聞爬取實例

# 實例:獲取騰訊新聞的標題和連接

from requests_html import HTMLSession

session = HTMLSession()

r = session.get("http://news.qq.com/")
# 經過CSS找到新聞標籤
news = r.html.find('.f14>a')
for new in news:
    print(new.text)  # 新聞標題
    print(new.absolute_links)  # 新聞鏈接

# 輸出內容:
# 重磅!2018年版自貿試驗區外資准入負面清單出爐
# {'http://new.qq.com/omn/FIN2018063001805300'}
# 津巴布韋7月1日起對中國遊客實行落地簽證政策
# {'http://news.qq.com/a/20180630/019314.htm'}
# 俠客島:據說特朗普要見普京?這首歌送給他們
# {'http://new.qq.com/omn/20180630A1GASD00'}
# 高等教育史上大動做:工科生「土」帽子要摘了
# {'http://new.qq.com/omn/20180630G07FLY00'}
# 日本小型火箭升空後4秒墜毀爆炸 現場火光沖天
# {'http://new.qq.com/omn/20180630V157BT00'}
# 洞庭湖「私家湖泊」新進展:剷除非法堤壩
# {'http://new.qq.com/omn/20180630A0ILA600'}
# 討論很熱烈!個稅法修訂徵求意見數已超1.3萬條
# {'http://new.qq.com/zt/template/?id=FIN2018061901656900'}
相關文章
相關標籤/搜索