【发布时间】:2021-01-04 23:37:44
【问题描述】:
这是我的代码:
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
import requests
url = 'https://en.wikisource.org/wiki/Main_Page'
r = requests.get(url)
Soup = BeautifulSoup(r.text, "html5lib")
List = Soup.find("div",class_="enws-mainpage-widget-content", id="enws-mainpage-newtexts-content").find_all('a')
ebooks=[]
i=0
for ebook in List:
x=ebook.get('title')
for ch in x:
if(ch==":"):
x=""
if x!="":
ebooks.append(x)
i=i+1
inputnumber=0
while inputnumber<len(ebooks):
print(inputnumber+1, " - ", ebooks[inputnumber])
inputnumber=inputnumber+1
input=int(input("Please select a book: "))
selectedbook = Soup.find("a", title=ebooks[input-1])
print(selectedbook['title'])
url1 = "https://en.wikisource.org/"+selectedbook['href']
r1 = requests.get(url1)
Soup1 = BeautifulSoup(r1.text, "html5lib")
List1 = Soup1.find("div", class_="prp-pages-output").find_all('p')
words=str(List1)
ebook1= open('ebook1.txt', 'w', encoding="utf-8")
ebook1.write(words)
ebook1.close()
来自这个网站:https://en.wikisource.org/wiki/May_(M%C3%A1cha) 我想获取故事的文本,但结果我在创建的文件中得到了这个:
[<p><span style="font-size:249%;"><b>May</b></span>
</p>, <p><span style="font-size: 144%;">A ROMANTIC POEM</span><br/>
<span style="font-size: 92%;"><i>by</i></span><br/>
<span style="font-size: 120%;"><span class="plainlinks"><a href="/wiki/Author:Karel_Hynek_M%C3%A1cha" title="Author:Karel Hynek Mácha">KAREL HYNEK MACHA</a></span></span>
</p>, <p><span style="font-size: 83%;"><i>Translated from the Czech by</i></span><br/>
<span style="font-size: 120%;"><span class="plainlinks"><a href="/wiki/Author:Roderick_Aldrich_Ginsburg" title="Author:Roderick Aldrich Ginsburg">RODERICK A. GINSBURG</a></span></span></p>]
似乎有两个具有相同类的 div,但我想获得第二个。代码采用第一个。我该怎么办?
【问题讨论】:
-
我想如果你用
Soup1.find_all(class_='prp-pages-output')[1]替换Soup1.find("div", class_="prp-pages-output")你会得到第二个div。 -
文件 "homework.py",第 32 行,在
List1 = Soup1.find_all("div", class_="prp-pages-output").find_all('p') 文件“C:\Users\Özdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\bs4\element.py”,第 2173 行,在 getattr raise AttributeError(AttributeError: ResultSet object has no attribute 'find_all '。您可能将元素列表视为单个元素。当您打算调用 find() 时是否调用了 find_all()?当我这样做时出现此错误 -
当你运行下面我的回答中的代码时,你仍然得到
AttributeError吗? -
你今天和昨天都问了几个关于 python 网页抓取的问题。如果您之前的问题得到准确和正确的回答,请接受对您之前问题的回答。
-
@ShaneBishop 是的,我有,每个问题都是不同的。我正在努力学习一些东西,而且我是新手,所以我认为可以提问。
标签: python web web-scraping