我有一个RSS提要,我正在尝试用bs4
解析。提要中的每个项目都有这种结构,据我所知,所有标签始终存在。
<item>
<title>From impeachment, to pandemic, to riots, wildfires and killer hornets, 2020 is proving to be a doozy</title>
<link>https://www.washingtontimes.com/news/2020/jun/2/from-impeachment-to-pandemic-to-riots-wildfires-an/?utm_source=RSS_Feed&utm_medium=RSS</link>
<description><p>Can 2020 get crazier? You bet. We&rsquo;re just getting started.</p> <p>If you wrote a screenplay of what&rsquo;s happened so far in 2020 and gave it to Hollywood producers, they&rsquo;d laugh you right out of the room.</p> <p>&ldquo;So, your movie,&rdquo; they&rsquo;d say, &ldquo;has the president of the United States being impeached, ...</description>
<dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Joseph Curl</dc:creator>
<pubDate>Tue, 02 Jun 2020 16:51:24 -0400</pubDate>
<guid>https://www.washingtontimes.com/news/2020/jun/2/from-impeachment-to-pandemic-to-riots-wildfires-an/?utm_source=RSS_Feed&utm_medium=RSS</guid>
</item>
我正在尝试使用以下代码解析每个item
标签:
xml = BeautifulSoup(resp, "html.parser")
for item in xml.findAll("item"):
curs.execute("INSET INTO rss_items (title, link, description, dc_creator, pub_date, guid)
VALUES (%s, %s, %s, %s, %s, %s, %s)",
(
item.find("title").text,
item.find("link").text,
item.find("description").text,
item.find("dc:creator").text,
item.find("pubDate").text,
item.find("guid").text
))
conn.commit()
我知道bs4
正在正确读取提要,就好像我使循环的主体成为一个简单的print(item.find("title").text)
,然后打印每个item
标签的标题。然而,当我在服务器上运行此代码时,出现以下错误:
Traceback (most recent call last):
File "inserts.py", line 21, in <module>
item.find("pubDate").text,
AttributeError: 'NoneType' object has no attribute 'text'
为什么会发生此错误,为什么只针对子标记pubDate
,而之前的所有item.find
调用似乎都成功?
在元素名称中使用小写字母而不是驼峰大小写,如下所示:
item.find("pubdate")
使用您提供的示例,它解决了问题。
根据文档:
"由于HTML标签和属性不区分大小写,因此所有三个HTML解析器都将标签和属性名称转换为小写。也就是说,标记将转换为 。如果要保留大小写或大写混合的标记和属性,则需要将文档解析为 XML。