【发布时间】:2021-09-15 17:11:43
【问题描述】:
感谢您的帮助。
我正在尝试根据两个或多个搜索字词从 Google 返回多个搜索结果。示例输入:
数字经济 gov.uk
数字经济gouv.fr
对于我输入的大约 50% 的搜索结果,下面的脚本运行良好。但是,对于剩余的搜索字词,我收到:
ValueError: 数组的长度必须相同
关于如何解决这个问题的任何想法?
output_df1=pd.DataFrame()
for input in inputs:
query = input
#query = urllib.parse.quote_plus(query)
number_result = 20
ua = UserAgent()
google_url = "https://www.google.com/search?q=" + query + "&num=" + str(number_result)
response = requests.get(google_url, {"User-Agent": ua.random})
soup = BeautifulSoup(response.text, "html.parser")
result_div = soup.find_all('div', attrs = {'class': 'ZINbbc'})
links = []
titles = []
descriptions = []
for r in result_div:
# Checks if each element is present, else, raise exception
try:
link = r.find('a', href = True)
title = r.find('div', attrs={'class':'vvjwJb'}).get_text()
description = r.find('div', attrs={'class':'s3v9rd'}).get_text()
# Check to make sure everything is present before appending
if link != '' and title != '' and description != '':
links.append(link['href'])
titles.append(title)
descriptions.append(description)
# Next loop if one element is not present
except:
continue
to_remove = []
clean_links = []
for i, l in enumerate(links):
clean = re.search('\/url\?q\=(.*)\&sa',l)
# Anything that doesn't fit the above pattern will be removed
if clean is None:
to_remove.append(i)
continue
clean_links.append(clean.group(1))
output_dict = {
'Search_Term': input,
'Title': titles,
'Description': descriptions,
'URL': clean_links,
}
search_df = pd.DataFrame(output_dict, columns = output_dict.keys())
#merging the data frames
output_df1=pd.concat([output_df1,search_df])
基于这个答案:Python Pandas ValueError Arrays Must be All Same Length 我也尝试过使用 orient=index。虽然这不会给我数组错误,但它只为每个搜索结果返回一个响应:
a = {
'Search_Term': input,
'Title': titles,
'Description': descriptions,
'URL': clean_links,
}
search_df = pd.DataFrame.from_dict(a, orient='index')
search_df = search_df.transpose()
#merging the data frames
output_df1=pd.concat([output_df1,search_df])
编辑:根据@Hammurabi 的回答,我能够为每个输入至少提取 20 个返回值,但这些似乎是重复的。知道我如何将唯一返回迭代到每一行吗?
df = pd.DataFrame()
cols = ['Search_Term', 'Title', 'Description', 'URL']
for i in range(20):
df_this_row = pd.DataFrame([[input, titles, descriptions, clean_links]], columns=cols)
df = df.append(df_this_row)
df = df.reset_index(drop=True)
##merging the data frames
output_df1=pd.concat([output_df1,df])
关于如何解决数组错误以使其适用于所有搜索词的任何想法?或者我如何使 orient='index' 方法适用于多个搜索结果 - 在我的脚本中,我试图为每个搜索词提取 20 个结果。
感谢您的帮助!
【问题讨论】:
标签: python pandas dataframe valueerror