2016-09-24 66 views
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() 
+0

''||無效Python語法。改爲使用'或'。 –

+0

@JF工作!謝謝!不再收到該錯誤,但由於某種原因,谷歌搜索不輸出任何內容。我試圖通過硬編碼的價值來搜索,而不是從文本文件獲得輸入,並且工作,但從文件輸入搜索不起作用。這可能是因爲\ n是在一個文本文件中? –

+0

您在拆分時刪除了換行符,您需要添加一些示例輸入。也不知道你爲什麼使用查找 –

回答

0

您可以使用谷歌模塊的Python爲谷歌搜索

from google import search 
for url in search(query, stop=10): 
    print url