我已经在python
中编写了一个脚本,以从网页中抓取Plot
中的描述。问题是描述位于几个p
标记内。还有其他p
标签,我也不想删除。一旦我的脚本完成了对Plot
的描述的解析,它就应该停止。但是,我的下面脚本从p
部分开始解析所有Plot
标签。
如何限制我的脚本仅分析Plot
的描述?
这是我写的:
import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Alien_(film)"
with requests.Session() as s:
s.headers={"User-Agent":"Mozilla/5.0"}
res = s.get(url)
soup = BeautifulSoup(res.text,"lxml")
plot = [item.text for item in soup.select_one("#Plot").find_parent().find_next_siblings("p")]
print(plot)
答案 0 :(得分:1)
如果您不是必须使用beautifulSoup,则可以在下面尝试获取所需的文本内容
{{1}}
答案 1 :(得分:1)
您可以在下一个标题之前选择段落,例如
with requests.Session() as s:
s.headers={"User-Agent":"Mozilla/5.0"}
res = s.get(url)
soup = BeautifulSoup(res.text,"lxml")
plot_start = [item for item in soup.select_one("#Plot").find_parent().find_next_siblings()]
plot = []
for item in plot_start:
if item.name != 'h2':
plot.append(item.text)
else:
break
print(plot)