如何使用Pandas找到一个国家的坐标?

2024-10-04 01:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

错误:

Traceback (most recent call last):
  File "fetchcord.py", line 18, in <module>
    coordinates = search1.find('div', {"class": "Z0LcW"}).get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

代码:

import pandas as pd, requests as requests
import urllib
from bs4 import BeautifulSoup

datasetLocation = "D:\Projects\Corona\public\scripts\coronaprac.csv";
df = pd.read_csv(datasetLocation, 'coronaprac', engine='python')

userAgent = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like 
    Gecko) Chrome/73.0.3683.103 Safari/537.36'}
searchURL = "https://www.google.com/search?q="

for x in range(0, len(df.index)):

    if str(df.iloc[-1]) is None:
        print(str(df.iloc[x, 0]) + " | " + str(df.iloc[x, 2]) + " | " + str(df.iloc[x, 3]))

    else:
        country = df.iloc[x, 0]
        search1 = BeautifulSoup(requests.get(searchURL + country + '+coordinates', 
            headers=userAgent).text, 'html.parser')
        coordinates = search1.find('div', {"class": "Z0LcW"}).get_text()
        df.loc[x, 'Coordinates'] = coordinates
        print(df.iloc[x, 0] + " | " + coordinates)
    df.to_csv(datasetLocation, index=False)

Tags: csvtextinimportdivdfgetfind