我正在查找一个特定的类。我可以使用相同的语句与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'
1条答案
按热度按时间wvt8vs2t1#
在你的代码中需要纠正的事情:
1.您使用的类名不正确。使用
soup.find(class_="subNav__outer")
代替soup.find(class_="subNav_outer")
。1.最好使用
results.prettify()
而不是results.prettify
,类似地使用abclistings.prettify()
而不是abclistings.prettify
。您不需要将结果类型转换为str
,因为prettify()
本身返回str
。下面是你的代码的一个更优化的版本: