requests
scrapy
兩個解析 html 文件的有力工具:lxml & beautifulsoup4,一切暴露在網際網路中的資料,都不是絕對安全的,但絕對是需要費腦筋才需要得到的,爬蟲很簡單學,真正難的是反爬。
requests 模組常用方法單次請求(每傳送一次請求,就需要呼叫一次)
多次請求(可以重複呼叫任何請求方法)
以上兩種所包含的任何方法或者類,除去 get() 和 post() 等,以請求型別命名的方法不需要傳遞請求型別這個引數,對於其他的則需要。其他引數都可以傳遞,比如(
#
號標記是必須引數):引擎從排程器中取出乙個鏈結(url)用於接下來的抓取
爬蟲解析response
解析出實體(item),則交給實體管道進行進一步的處理
解析出的是鏈結(url),則把url交給排程器等待抓取
定位到專案中的
settings.py
檔案,修改以下值編輯爬蟲檔案(# 修改請求頭
user_agent =
'mozilla/5.0 (macintosh; intel mac os x 10.14; rv:67.0) gecko/20100101 firefox/67.0'
# 關閉爬蟲規則
robotstxt_obey =
false
spiders/douban.py
)啟動爬蟲# -*- coding: utf-8 -*-
class
doubanspider
(scrapy.spider)
:# 爬蟲名稱
name =
'douban'
# 爬蟲範圍
allowed_domains =
['www.douban.com'
]# url 列表
start_urls =
['']def
parse
(self, response)
:# 該方法主要用來解析頁面內容
# 輸出頁面內容
(response.text)
頁面內容的解析# 帶日誌輸出
scrapy crawl douban
# 不帶日誌輸出
scrapy crawl douban --nolog
改# -*- coding: utf-8 -*-
import scrapy
from lxml import etree
from bs4 import beautifulsoup
class
doubanspider
(scrapy.spider)
:# 爬蟲名稱
name =
'douban'
# 爬蟲範圍
allowed_domains =
['www.douban.com'
]# url 列表
start_urls =
['']def
parse
(self, response)
:# 1 scrapy 的 xpath 解析,獲取熱點鏈結
( response.xpath(
'//div[@id="anony-sns"]//div[@class="albums"]//a/@href'
).extract())
# or
( response.xpath(
'//div[@id="anony-sns"]//div[@class="albums"]//a/@href'
).getall())
page_etree = etree.html(response.text)
( page_etree.xpath(
'//div[@id="anony-sns"]//div[@class="notes"]//a/@href'))
# 3 beautifulsoup4 解析,獲取熱點話題鏈結
soup = beautifulsoup(response.text)
parents_div = soup.find(
'div'
, attrs=
) link_list = parents_div.find_all(
'a', attrs=
(list
(map
(lambda link: link.attrs[
'href'
], link_list)
))
Python筆記 爬蟲
用到的庫 urllib。在python3.x中 urlretrieve函式也在urllib.request下,因此只需要匯入request即可。from urllib import request基本的思路是 用request.urlopen 開啟網頁 url.read decode 得到網頁原始碼...
Python爬蟲筆記
import requests 匯入requests模組 1.傳送請求 import requests r requests.get 2.定製headers 這種情況適用於爬取返回的結果出現 抱歉 無法訪問 等字眼時,這時需要模擬乙個介面伺服器自行爬取的狀態 import requests r re...
python筆記 爬蟲
正規表示式 ref 爬ref 更新了一下 版本,刪去了函式調取。1.urllib re實現 import urllib.request import re url 根據url獲取網頁html內容 page urllib.request.urlopen url html page.read 從html...