如何在Python/BS4的我的网页抓取脚本中添加代理和头文件?

问题描述:

我曾经使用BeautifulSoup4和Python来解析本地html文件几次。现在我想使用代理来抓取网站。 (总共需要400个请求/ IP请求被阻止后)如何在Python/BS4的我的网页抓取脚本中添加代理和头文件?

在用普通的'sleep'减慢我的脚本之后,我想使用代理,但是我从来没有这样做过,而且确实需要一些帮助这里。我尝试了两种方法,从堆栈溢出问题的帮助:

方法1
此方法不与其他网站合作,但不会下载数据。当我“打印”我收到的数据时,它会打印“响应[200]”。当我用真实网站尝试这种方法时,它确实返回错误:“最大重试次数超过了url:”我怀疑代理没有被正确处理。当我尝试阅读html时,出现以下错误。

page_html = response.read()
AttributeError: 'Response' object has no attribute 'read'

response = requests.get(URL, proxies=PROXY, headers=HEADER) 

方法2
我能下载另一个网页,但我无法从原来的网页(这阻止我)下载。我认为脚本存在错误,代理处理不正确。无论是真实的IP发送到网站,或无法连接到代理:

response = urllib.request.urlopen(urllib.request.Request(url, None, header, proxy)) 

我的剧本确实是这样的:

HEADER = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'} 
URL = "https://www.website.php" 
PROXY = {"https": "https//59.110.7.190:1080"} 

#response.close() Is this even necessary 

page_html = response.read() # With Method 1 I also tried response.text which resulted in "str is not callable" 
response.close() 
page_soup = soup(page_html, "html.parser") 

adresses = page_soup.findAll("li", {"class":"list-group-item"}) 

for address in adresses: 
    try: 
     #parsing the html 
    except (TypeError): 
     f.write("invalid data" + "\n") 
time.sleep(random.randint(1, 10)) 

错误我通常是这样的:

requests.exceptions.ProxyError: HTTPSConnectionPool(host='www.firmendb.de', port=443): Max retries exceeded with url: /[website.php] (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)))

Process finished with exit code 1

我假设我搞砸了脚本的代理部分。它在我尝试实现它之前确实有效。因为在我的主要问题之前我从来没有这样做过,所以代理部分是否正确?我从以下网站获得代理:https://free-proxy-list.net/

  • 如何从这些列表中选择代理?
  • 如何连接到代理?
  • 有关代理提供者使用的任何建议?
  • 我的脚本的任何建议?
+1

您可以验证您的IP已变更或请求有你的真实IP?你可以使用这样的网站:https://www.whatismyip.com/my-ip-information/?iref=home找出你的IP是否改变了。 –

+0

另外请记住,许多代理(特别是免费代理)用于恶意目的,因此在黑名单上。 – charlesreid1

+0

@ Christos Papoulas:好点;我对它进行了测试,并让我真正的知识产权得到了回复这意味着脚本中的代理设置被忽略。你知道为什么吗?你知道一个在线帮助或类似的代理和刮吗?为了测试代理是否正常工作,我使用了这个命令:response = requests.get(url,proxies = {“https”:“https://46.163.119.138:3128”},headers = header) – Marco

感谢评论!错误是,我没有考虑proxys会多久改变一次。我在测试脚本之前以我的脚本方式编写代理。

为了帮助其他人,这就是剧本在Pyhton3中的样子。
当然,HEADER/URL/PROXY也可以是一个列表,然后通过for循环馈送。

HEADER = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'} 
URL = "https://www.website.php" 
PROXY = {"https": "https//59.110.7.190:1080"} 

response = requests.get(URL, proxies=PROXY, headers=HEADER) 
page_html = response.text 
page_soup = soup(page_html, "html.parser") 

adresses = page_soup.findAll("li", {"class":"list-group-item"}) #for example 

for address in adresses: 
    try: 
     #parsing the html 
    except (TypeError): 
     f.write("invalid data" + "\n") 
time.sleep(random.randint(1, 10))