【发布时间】:2018-04-20 17:14:42
【问题描述】:
我正在做一个 Python 练习,它要求我通过网络抓取从 Google 新闻网站获取头条新闻并打印到控制台。 当我这样做时,我只是使用 Beautiful Soup 库来检索新闻。那是我的代码:
import bs4
from bs4 import BeautifulSoup
import urllib.request
news_url = "https://news.google.com/news/rss";
URLObject = urllib.request.urlopen(news_url);
xml_page = URLObject.read();
URLObject.close();
soup_page = BeautifulSoup(xml_page,"html.parser");
news_list = soup_page.findAll("item");
for news in news_list:
print(news.title.text);
print(news.link.text);
print(news.pubDate.text);
print("-"*60);
但是由于不打印“链接”和“pubDate”,它一直给我错误。经过一番研究,我在 Stack Overflow 上看到了一些答案,他们说,由于网站使用 Javascript,除了 Beautiful Soup 之外,还应该使用 Selenium 包。 尽管不了解 Selenium 的真正工作原理,但我将代码更新如下:
from bs4 import BeautifulSoup
from selenium import webdriver
import urllib.request
driver = webdriver.Chrome("C:/Users/mauricio/Downloads/chromedriver");
driver.maximize_window();
driver.get("https://news.google.com/news/rss");
content = driver.page_source.encode("utf-8").strip();
soup = BeautifulSoup(content, "html.parser");
news_list = soup.findAll("item");
print(news_list);
for news in news_list:
print(news.title.text);
print(news.link.text);
print(news.pubDate.text);
print("-"*60);
但是,当我运行它时,会打开一个空白浏览器页面,并将其打印到控制台:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(Driver info: chromedriver=2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed),platform=Windows NT 6.3.9600 x86_64)
【问题讨论】:
-
我相信您拥有的链接(带有
/rss)是一个 XML 文件,因此其中没有使用 javascript -
那么,如何让“news.link.text”和“news.pubDate.text”同时出现在我的输出中?当我只使用 Beautiful Soup 打印它们时,“news.title.text”打印正常,链接打印一个新行,而 pub date 是一个例外,因为它返回 None 类型,我在其中使用了“.text”。跨度>
标签: python selenium web-scraping beautifulsoup