无法限制我的脚本来解析网页中的特定部分

时间:2018-09-17 14:17:35

标签: python python-3.x web-scraping beautifulsoup

我已经在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)

2 个答案:

答案 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)