用Python刮网,靓汤,硒不起作用

2024-06-16 11:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个Python练习,它要求我通过web抓取并打印到控制台来获得Google新闻网站的最新消息。 在我做这件事的时候,我只是用美丽的汤库检索新闻。这是我的准则:

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);

但它不打印“link”和“pubDate”,一直给我错误。经过一番研究,我在这里看到了一些关于堆栈溢出的答案,他们说,由于网站使用Javascript,除了靓汤之外,还应该使用Selenium包。 尽管不了解Selenium的实际工作原理,我还是将代码更新如下:

^{pr2}$

但是,当我运行它时,会打开一个空白的浏览器页面并将其打印到控制台:

 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)

Tags: textimporturl网站requestpagexmlurllib
2条回答

只需将^{}^{}一起使用。在

from bs4 import BeautifulSoup
import requests

r = requests.get('https://news.google.com/news/rss')
soup = BeautifulSoup(r.text, 'xml')
news_list = soup.find_all('item')

# do whatever you need with news_list

我刚试过,下面的代码对我有用。items =这句话太可怕了,请提前道歉。但现在它起作用了。。。在

编辑 刚刚更新了代码段,您可以使用ElementTree.iter('tag')来迭代所有具有{}的节点:

import urllib.request
import xml.etree.ElementTree

news_url = "https://news.google.com/news/rss"
with urllib.request.urlopen(news_url) as page:
    xml_page = page.read()

# Parse XML page
e = xml.etree.ElementTree.fromstring(xml_page)

# Get the item list
for it in e.iter('item'):
    print(it.find('title').text)
    print(it.find('link').text)
    print(it.find('pubDate').text, '\n')

EDIT2:Discussion图书馆的个人偏好
就个人而言,对于那些我必须在其中做工作的交互式/动态页面(单击此处,填写表单,获得结果,…):我使用selenium,而且通常我不需要使用bs4,因为您可以直接使用selenium来查找和解析您要查找的web的特定节点。在

我使用bs4requests(而不是urllib.request)来在我不想安装整个webdriver的项目中解析更多静态网页。在

使用urllib.request没有什么错,但是requests(参见这里的docs)是最好的python包之一(在我看来),它是如何创建一个简单而强大的API的好例子。在

相关问题 更多 >