for
当我尝试运行上面的代码时,没有显示错误消息。显示的唯一内容是runfile(myfilepath),wdir(anotherpath)。我期待输出打印名称,在这种情况下将是“唐纳德特朗普”。任何帮助或建议?我使用spyder(python 3.6)作为我的平台。
答案 0 :(得分:1)
这部分代码
except:
pass
有效地抑制错误消息。
答案 1 :(得分:0)
您的max-stale
应为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