python-3.x 无法使用BeautifulSoup查找(class_)属性

xwmevbvl  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(218)

我正在查找一个特定的类。我可以使用相同的语句与find(id),但类返回什么,所以美化错误了

import requests
from bs4 import BeautifulSoup

URL = "https://abcnews.go.com/Politics"
page = requests.get(URL)

# Testing Write to file from bs4
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="abcnews")
newresults = results.prettify
prettyresults = str(newresults)

abc_file = open("abc_pol.html", "wt")
n = abc_file.write(prettyresults)
abc_file.close()

# Listings

abclistings = soup.find(class_ = "subNav_outer")
newlistings = abclistings.prettify
prettylistings = str(abclistings)

abc_listings_file = open("ABC_Listings.html", "wt")
w = abc_listings_file.write(prettylistings)
abc_listings_file.close()

print(prettylistings)
$ /home/nicholas/Documents/Dev/Py/GN/bin/python /home/nicholas/Documents/Dev/Py/GN/abcnews.py
Traceback (most recent call last):
  File "/home/nicholas/Documents/Dev/Py/GN/abcnews.py", line 20, in <module>
    newlistings = abclistings.prettify
                  ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'prettify'
wvt8vs2t

wvt8vs2t1#

在你的代码中需要纠正的事情:
1.您使用的类名不正确。使用soup.find(class_="subNav__outer")代替soup.find(class_="subNav_outer")
1.最好使用results.prettify()而不是results.prettify,类似地使用abclistings.prettify()而不是abclistings.prettify。您不需要将结果类型转换为str,因为prettify()本身返回str
下面是你的代码的一个更优化的版本:

import requests
from bs4 import BeautifulSoup

URL = "https://abcnews.go.com/Politics"
page = requests.get(URL)

soup = BeautifulSoup(page.content, "html.parser")

results = soup.find(id="abcnews")
with open("abc_pol.html", "wt") as f:
    f.write(results.prettify())

abclistings = soup.find(class_="subNav__outer")
with open("ABC_Listings.html", "wt") as f:
    f.write(abclistings.prettify())

相关问题