簡體   English   中英

Selenium Webdriver / Beautifulsoup +網頁抓取+錯誤416

[英]Selenium Webdriver / Beautifulsoup + Web Scraping + Error 416

我正在使用帶Proxy的 Python中的Selenium Webdriver進行Web抓取。

我想使用此抓取功能瀏覽單個網站的1萬多頁。

問題是使用此代理,我只能發送一次請求。 當我在同一鏈接或此站點的另一個鏈接上發送另一個請求時,我在1-2小時內收到416錯誤(使用防火牆的IP阻止類)。

注意:我可以使用此代碼來抓取所有普通站點,但是此站點具有某種安全性,因此無法進行抓取。

這是代碼。

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()

任何解決方案??

Selenium對我沒有幫助,所以我通過使用beautifulsoup解決了這個問題,該網站在收到請求時就使用安全性來阻止代理,因此,只要服務器阻止了請求的代理,我就會不斷更改proxyurlUser-Agent

我在這里粘貼我的代碼

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. 很少有服務器僅接受特定的國家/地區代理,就我而言,我使用的是來自美國的代理

這個過程可能很慢,但是您仍然可以抓取數據

通過以下鏈接中的416錯誤問題,似乎是某些緩存的信息(可能是cookie)造成了問題。 您可以首次發送請求,隨后的發送請求將失敗。

https://webmasters.stackexchange.com/questions/17300/what-are-the-causes-of-a-416-error 416請求的范圍不滿足

嘗試通過設置首選項或在每次發送請求后刪除cookie來選擇不保存cookie。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM