gpt4 book ai didi

python - BeautifulSoup 对象中未打印链接属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:36 26 4
gpt4 key购买 nike

我正在编写一个程序,该程序将从 google 新闻中获取头条新闻。它应该打印文章的标题和链接。但是,它不会打印链接。

import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

news_url="https://news.google.com/news/rss"
Client=urlopen(news_url)
xml_page=Client.read()
Client.close()

soup_page=soup(xml_page,"lxml")
news_list=soup_page.findAll("item")
# Print news title, url and publish date
for news in news_list:
print(news.title.text)
print(news.link.text)
print("-"*10)

这是一个输出行的例子

Following Falcon 9 Saturday launch, CRS-17 Dragon arrives at the ISS

----------

它应该打印标题和链接。但它只打印标题

最佳答案

此 html 的结构很奇怪,但是如果您将代码中的 for 循环更改为:

for news in news_list:
link = news.select_one('title')
print(link.text)
print(link.next_sibling.next_sibling)
print("-"*10)

您应该获得带有链接的标题。

关于python - BeautifulSoup 对象中未打印链接属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com