Mit*_*hah 10 python beautifulsoup scrapy web-scraping selenium-webdriver
我正在使用带有代理的 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()
Run Code Online (Sandbox Code Playgroud)
任何解决方案
Selenium对我没有帮助,所以我通过使用beautifulsoup解决了这个问题,网站在收到请求时使用安全性来阻止代理,所以 每当服务器阻塞请求代理时我都在不断更改proxyurl和User-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
Run Code Online (Sandbox Code Playgroud)
注意 :
更改代理和用户代理并仅使用最新更新的代理
很少有服务器只接受特定的国家代理,在我的情况下我使用的是来自美国的Proxies
这个过程可能很慢,但你可以废弃数据