《Python网络数据采集》读后总结 --第12章避免爬虫的抓取陷阱

浏览: 2589

这章<如何避免爬虫的抓取陷阱>,我觉得最重要的就是这句Looking Like a Human,一般的网站是不会屏蔽人的正常操作的,如何让网站把你的操作当做正常的操作就是要点。


主要说了4点方法:

Adjust Your Headers

Handling Cookies

Timing Is Everything

Common Form Security Features--注意表单的提交内容


Adjust Your Headers

可以通过这个网站https://www.whatismybrowser.com 查看你的header是信息,这是我的浏览器的信息。


User-Agent是最常见的检测,可以通过如下代码指定:

#1-headers.py
import requests
from bs4 import BeautifulSoup
session = requests.Session()
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)
                         AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
           "Accept":"text/html,application/xhtml+xml,application/xml;
                     q=0.9,image/webp,*/*;q=0.8"}
url = "https://www.whatismybrowser.com/
       developers/what-http-headers-is-my-browser-sending"
req = session.get(url, headers=headers)
bsObj = BeautifulSoup(req.text)
print(bsObj.find("table",{"class":"table-striped"}).get_text)

Handling Cookies

可以通过Chrome的插件 :Edit‐ThisCookie,查看修改你的cookie

#2-seleniumCookies.py.txt
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path='<Path to Phantom JS>')
driver.get("http://pythonscraping.com")
driver.implicitly_wait(1)
print(driver.get_cookies())
savedCookies = driver.get_cookies()
driver2 = webdriver.PhantomJS(executable_path='<Path to Phantom JS>')
driver2.get("http://pythonscraping.com")
driver2.delete_all_cookies()
for cookie in savedCookies:
    driver2.add_cookie(cookie)
driver2.get("http://pythonscraping.com")
driver.implicitly_wait(1)
print(driver2.get_cookies())

Timing Is Everything

模拟人的操作,最重要是人的动作不会这么快,使用sleep

time.sleep(3)

Common Form Security Features(表单的一些安全属性识别)

为了反扒虫,一些网站在提交表单上会使用一些特殊手段(可以使用Chrome’s Networkinspector查看):

1.包含随机值的隐含字段(Hidden Input Field Values)

2.Avoiding Honeypots

例如:使用一个不可见的form如果用户提交了这个表单,就识别出爬虫,进而可以屏蔽IP等

最后列了一下避免爬虫的抓取陷阱检查清单:

1.检查页面是否由javascript生成

2.检查提交的表单是否包含所有应该提交的字段,包括隐含字段

可以使用Chrome’s Networkinspector 去检查

3.如果某些站点,session保持不住,注意cookie

4.如果经常遇到HTTP错误,特别是403 Forbidden errors,可能Ip被封了

  首先换一个IP,谈后为了避免再次block,确认

  a.不要太快的访问

  b.修改你的headers

  c.不要去触发Honeypots

  d.最后和网络管理员联系^-^


示例:

1-headers.py
2-seleniumCookies.py
3-honeypotDetection.py
推荐 3
本文由 seng 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册