1
我对Python相当陌生,所以IDE的错误没有多大意义。Python Beautifulsoup搜索谷歌
我有两个文本文件:
text2.txt <------- contains list of company names
text1.txt <------- after executing the program, this should be filled with url
下面这个脚本的目的是作为输入公司从text2.txt名称列表,和谷歌的名字用字一起“新闻发布会”。
然后,python脚本应该只为每个公司名称写入1个url到text1.txt,并且该url应该包含单词“press”或“release”。
该脚本的目标是为每个公司名称查找新闻稿URL。
我得到无效的语法使用“||”即使我删除了if语句,谷歌的URL也没有被发现或写入数组。有人可以建议我做错了什么吗?下面是代码:
import requests
from bs4 import BeautifulSoup
lines = open("test2.txt").read().splitlines()
links = []
for line in lines:
r = requests.get('https://www.google.com/search?q={}&gbv=1&sei=YwHNVpHLOYiWmQHk3K24Cw'.format((line + " press release").replace(" ", "+")))
soup = BeautifulSoup(r.text, "html.parser")
for item in soup.find_all('h3', attrs={'class': 'r'}):
i = (item.a['href'][7:]).find("release")
b = (item.a['href'][7:]).find("press")
if (i != -1 || b != -1):
links.append(item)
break;
f = open("test.txt","w")
for item in links:
f.write("%s\n" % item)
f.close()
''||无效Python语法。改为使用'或'。 –
@JF工作!谢谢!不再收到该错误,但由于某种原因,谷歌搜索不输出任何内容。我试图通过硬编码的价值来搜索,而不是从文本文件获得输入,并且工作,但从文件输入搜索不起作用。这可能是因为\ n是在一个文本文件中? –
您在拆分时删除了换行符,您需要添加一些示例输入。也不知道你为什么使用查找 –