2017-05-29 71 views
0
import requests 
from bs4 import BeautifulSoup 

url = "https://twitter.com/realDonaldTrump?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor" 

r = requests.get(url) 

soup = BeautifulSoup(r.content, "html.parser") 

links = soup.find_all("a") 

g_data = soup.find_all("div", {"class": "content"}) 

n_data = soup.find_all("strong", {"class": "fullname show-popup-with-id "}) 

c_data = soup.find_all("p", {"class": "TweetTextSize TweetTextSize--normal js-tweet-text tweet-text"}) 

for item in g_data: 

    try: 

     print(item.contents[0].find_all(n_data)[0].text) 

    except: 

     pass 

當我試着運行上面的代碼,沒有顯示錯誤信息。唯一顯示的是runfile(myfilepath),wdir(另一個路徑)。我期待輸出的名字在本例中是「唐納德特朗普」。任何幫助或建議?我使用spyder(python 3.6)作爲我的平臺。蟒蛇 - 沒有輸出也沒有錯誤信息

+0

實際上,你與你的try塊沉默的所有錯誤。 –

+0

你是什麼意思?順便說一句,我把上面的代碼放在了更好的視覺上。 – NewbieCoder

回答

0

print(item.contents[0].find_all(n_data)[0].text)應該是print(item.find_all("strong", {"class": "fullname show-popup-with-id "})[0].text)

import requests 
from bs4 import BeautifulSoup 

url = "https://twitter.com/realDonaldTrump?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor" 

r = requests.get(url) 
soup = BeautifulSoup(r.content, "html.parser") 

links = soup.find_all("a") 
g_data = soup.find_all("div", {"class": "content"}) 
n_data = soup.find_all("strong", {"class": "fullname show-popup-with-id "}) 
c_data = soup.find_all("p", {"class": "TweetTextSize TweetTextSize--normal js-tweet-text tweet-text"}) 

for item in g_data: 
    try: 
     print(item.find_all("strong", {"class": "fullname show-popup-with-id "})[0].text) # chain the n_data here 
    except: 
     pass 

輸出將是

Donald J. Trump ... ... ... Donald J. Trump

+0

嗨,我試過了,它通過了!非常感謝你 – NewbieCoder

+1

Yeap它的工作!謝謝! – NewbieCoder

1

代碼

except: 

     pass 

的這部分有效地抑制錯誤消息。

+0

嗨,我試圖帶走異常,並會有「解析時意外的EOF」的結果。但是,當我拿出嘗試,我會有''NavigableString'對象沒有屬性'find_all'「。對不起,如果這是一個愚蠢的問題,但即時通訊全新的python。 – NewbieCoder

+0

'try:'需要'除了:',所以「在解析時出現意想不到的EOF」(* EOF *表示*文件尾*) - 解析器期望'except:'但它永遠不會達到它。 – MarianD

+0

非常感謝你的解釋!我以某種方式期待它,但仍然做了試驗和錯誤,看它是否有效。無論如何,謝謝! – NewbieCoder