Python -bs4反爬虫解决方法

来源:互联网 发布:毛衣店铺推荐知乎 编辑:程序博客网 时间:2024/06/07 01:00

爬虫有时会遭遇两种情况,导致无法正常爬取
(1)IP封锁,(貌似美团会出现)
(2)禁止机器人爬取,(比如Amazon)

解决方法:
我们以下面文章里的爬虫代码为例
http://blog.csdn.net/co_zy/article/details/77150544
其中的getHTMLText()函数,更改如下,添加fakeHeaders ,proxies
这里的可以通过ip测试网站进行验证是否成功使用了代理 http://ip.chinaz.com/

def getHTMLText(self,url):        fakeHeaders = {'user-agent':'Mozilla/5.0'}        proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", }           try:            r = requests.get(url,headers = fakeHeaders , proxies=proxies,timeout=30)            r.raise_for_status()            r.encoding = r.apparent_encoding            return r.text        except:            return ""
原创粉丝点击