使用BeautifulSoup防止被Google抓取禁止

时间:2019-11-26 09:07:07

标签: python beautifulsoup proxy

我想用PythonBeautifulSoup制作Google新闻抓取工具,但我读过,我有可能被禁止。

我还读到我可以使用一些旋转代理和旋转IP地址来防止这种情况。 我唯一要做的就是旋转User-Agent。 您能告诉我如何添加旋转代理和旋转IP地址吗?

我知道应该在request.get()部分中添加它,但是我不知道如何。

这是我的代码:

from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=0

for page in range(1,5):

    page = page*10

    url = 'https://www.google.com/search?q={}&tbm=nws&sxsrf=ACYBGNTx2Ew_5d5HsCvjwDoo5SC4U6JBVg:1574261023484&ei=H1HVXf-fHfiU1fAP65K6uAU&start={}&sa=N&ved=0ahUKEwi_q9qog_nlAhV4ShUIHWuJDlcQ8tMDCF8&biw=1280&bih=561&dpr=1.5'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    headline_text = soup.find_all('h3', class_= "r dO0Ag")

    snippet_text = soup.find_all('div', class_='st')

    news_date = soup.find_all('div', class_='slp')

    print(len(news_date))

5 个答案:

答案 0 :(得分:1)

您可以使用Google提供的正确API进行搜索:

https://developers.google.com/custom-search/v1/overview

答案 1 :(得分:0)

如果您想学习网页抓取,最好选择其他网站,例如reddit或一些在线杂志。 Google新闻(及其他Google服务)受到良好的保护,不会被抓取,并且它们会定期更改类的名称,以防止您通过简单的方式进行操作。

答案 2 :(得分:0)

如果您的问题是“不被禁止怎么办?”,那么答案是“不要违反TOS”,这意味着完全不抓取内容并使用适当的搜索API。 根据您使用的IP地址,有一些“免费”的Google搜索用途。因此,如果您只抓取少量搜索,那应该没问题。

如果您的问题是“如何在请求模块中使用代理?”,那么您应该开始寻找here

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)

但这只是python方面,您需要自己设置一个Web代理(甚至更好的代理池),然后使用一种算法,例如,每N个请求选择一个不同的代理。

答案 3 :(得分:0)

您可以使用https://gimmmeproxy.com来旋转代理,它是python包装器:https://github.com/DeyaaMuhammad/GimmeProxyApi

proxy = GimmeProxyAPI(protocol="https")

proxies = {
  'http': proxy,
  'https': proxy
}

requests.get('https://example.org', proxies=proxies)

答案 4 :(得分:0)

一个更简单的技巧是在 Brave Tor 浏览器中使用 Google colab,然后查看结果,您将获得不同的 IP 地址。

因此,一旦您获得所需的数据,您就可以在 jupyter notebook、VS Code 或其他地方使用这些数据。

看,截图中的结果:

使用免费代理会出错,因为免费代理上的请求太多,因此,您必须每次都选择代理流量较低的不同代理,因此从数百个中选择一个是一项艰巨的任务。

>

Using free proxies will get an error because there are too many requests on the free proxies so, you have to pick every time different one whose proxy is getting lower traffic so that's a terrible task to chose one out of hundreds

使用 Brave Tor VPN 获得正确结果: Getting correct results with Brave Tor VPN

相关问题