使用Python网络抓取Google结果

时间:2020-06-17 16:51:41

标签: python web-scraping beautifulsoup

我想在给定的google结果图像中抓取所有距离。我可以刮擦第一个距离,但不能刮擦第二个和第三个距离。 我正在使用下面的代码刮擦第一距离。

def get_applications_json(category):
    applicationsByCategory = get_applications(category)
    applications = []
    if applicationsByCategory:
        for app in applicationsByCategory: 
            applications.append({
                "body" : app.body
            })

     return applications

Google result

1 个答案:

答案 0 :(得分:0)

您可以在soup.find()中使用正则表达式模式来查找距离(也可以设置User-Agent Http标头)。

例如:

import re
import requests
from bs4 import BeautifulSoup

url = 'https://www.google.com/search?hl=en&q=distance%20between%20zip%20codes%2075000%20paris%20and%2075016%20paris'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}
soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')

print(soup.find(text=re.compile(r'\d+\.\d+\s*km')))

打印:

15.8 km