从Google抓取包含日期范围的网址

时间:2020-03-08 19:25:59

标签: python web-scraping jupyter-notebook

是否可以通过Google搜索在某个时间范围内(例如从02-02-2018到02-03-2018)获得结果,从而避免HTTPSConnectionPool错误?

我当前正在使用以下代码

urls=[]
count=0

q='Brexit'

for url in search(q):
        r = requests.get(url, timeout=None)
        r.status_code
        count=count+1
        urls.append(url)   

最好在指定的时间范围内抓取网址。但是,由于出现以下错误,所以无法执行此操作:

HTTPSConnectionPool(host ='www .___。org',port = 443):最多重试一次 超出网址:/ Brexit /(由 NewConnectionError(':无法建立新的连接:[Errno 60] 操作超时'))

,我不知道是否可以修复它和/或如何修复。
您能否告诉我是否有一种方法可以避免以下错误消息并在指定的日期范围内获得结果?感谢您的时间。

1 个答案:

答案 0 :(得分:0)

使用日期概括查询。 因此,对于Google来说,您可以为特定日期设置范围运算符。

如果您的search函数只是request.get('https://google.com/search?q={}'.format(q)),则可以使用以下代码:

urls=[]
count=0

q='Brexit before:02-03-2018 after:02-02-2018'

for url in search(q):
        r = requests.get(url, timeout=None)
        r.status_code
        count=count+1
        urls.append(url)   

这将解决日期问题。对于错误,我认为您正在尝试获取href为'___'的网址。那可能只是一个错误的链接,所以我只添加一个try,除了阻止并记录它。因此,我将考虑进行更多过滤(使用BeautifulSoup以获得结果。 因此代码将是:

import request
from bs4 import BeautifulSoup

q='Brexit before:02-03-2018 after:02-02-2018'
req = request.get('https://google.com/search?q={}'.format(q), timeout=None)
soup = BeautifulSoup(req.content, 'html.parser')
hrefs = soup.find_all('a') # this is all the hrefs. 
for href in hrefs: 
     try: 
         r = requests.get(url)
     except Exception as e: 
         print(e)