Selenium Webdriver / Beautifulsoup + Web Scraping +错误416

时间:2015-09-23 11:42:23

标签: python selenium-webdriver web-scraping beautifulsoup scrapy

我正在使用Proxy在Python中使用selenium webdriver进行网页抓取。

我想使用此抓取功能浏览超过10k页的单个网站。

问题正在使用此代理我只能发送一次请求。当我在同一个链接或本网站的另一个链接上发送另一个请求时,我得到416错误(使用防火墙的块IP类型)1-2个小时。

注意:我可以使用此代码抓取所有正常网站,但此网站具有一定的安全性,这会阻止我进行抓取。

这是代码。

profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference(
                "network.proxy.http", "74.73.148.42")
profile.set_preference("network.proxy.http_port", 3128)
profile.update_preferences()
browser = webdriver.Firefox(firefox_profile=profile)
browser.get('http://www.example.com/')
time.sleep(5)
element = browser.find_elements_by_css_selector(
                '.well-sm:not(.mbn) .row .col-md-4 ul .fs-small a')
for ele in element:
    print ele.get_attribute('href')
browser.quit()

任何解决方案??

2 个答案:

答案 0 :(得分:5)

Selenium对我没有帮助,所以我使用beautifulsoup解决了这个问题,网站在收到请求时使用安全性阻止代理,所以我不断更改proxyurl和{ {3}}每当服务器阻止请求代理时。

我在这里粘贴我的代码

from bs4 import BeautifulSoup
import requests
import urllib2

url = 'http://terriblewebsite.com/'

proxy = urllib2.ProxyHandler({'http': '130.0.89.75:8080'})

# Create an URL opener utilizing proxy
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
request = urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15')
result = urllib2.urlopen(request)
data = result.read()
soup = BeautifulSoup(data, 'html.parser')
ptag = soup.find('p', {'class', 'text-primary'}).text
print ptag

注意:

  1. 更改代理和用户代理并仅使用最新更新的代理

  2. 很少有服务器只接受特定的国家/地区代理,在我的情况下我使用的是来自美国的代理

  3. 这个过程可能很慢,但你可以废弃数据

答案 1 :(得分:1)

通过以下链接中的416错误问题,似乎某些缓存信息(可能是Cookie)正在创建问题。您可以第一次发送请求,后续发送请求失败。

https://webmasters.stackexchange.com/questions/17300/what-are-the-causes-of-a-416-error 416 Requested Range Not Satisfiable

尝试在每次发送请求后设置首选项或删除Cookie,以选择不保存Cookie。

profile.set_preference("network.cookie.cookieBehavior", 2);