【问题标题】:How can I extract the text outside the <em> tag in BeautifulSoup如何在 BeautifulSoup 中提取 <em> 标记之外的文本
【发布时间】:2016-12-08 03:05:45
【问题描述】:

谁能帮我提取 From 之后的测试,我想提取发件人姓名。它位于 em 标签的外面。我正在使用 python BeautifulSoup 包。

这是网页链接:http://seclists.org/fulldisclosure/2016/Jan/0

我能够成功提取电子邮件标题,因为它位于标签中。 html 页面中没有其他 div 或类。

这是页面的html代码:

这是我尝试过的

def title_spider(max_pages):
    page = 0
    while page <= max_pages:
        url = 'http://seclists.org/fulldisclosure/2016/Jan/' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        for email_title in soup.find('b'):
            title = email_title.string
            print(title)

        for date_stamp in soup.em:
            date = date_stamp
            print(date)
        page += 1

title_spider(2)

`

【问题讨论】:

    标签: python beautifulsoup web-crawler


    【解决方案1】:

    你想要下一个兄弟,如果你想要特定 em 的 From 和 Date,你可以结合一个正则表达式:

    import re
    
    def title_spider(max_pages):
        for page in range(max_pages + 1):
            url = 'http://seclists.org/fulldisclosure/2016/Jan/{}'.format(page) 
            source_code = requests.get(url)
            plain_text = source_code.text
            soup = BeautifulSoup(plain_text, "html.parser")
            for email_title in soup.find('b'):
                title = email_title.string
                print(title)
    
            for em in soup.find_all("em", text=re.compile("From|Date")):
                print(em.text, em.next_sibling)
    

    这给了你:

    In [5]: title_spider(2)
    Alcatel Lucent Home Device Manager - Management Console Multiple XSS
    From : Uğur Cihan KOÇ <u.cihan.koc () gmail com>
    Date : Sun, 3 Jan 2016 13:20:53 +0200
    Executable installers/self-extractors are vulnerable^WEVIL  (case 17): Kaspersky Labs utilities
    From : "Stefan Kanthak" <stefan.kanthak () nexgo de>
    Date : Sun, 3 Jan 2016 16:12:50 +0100
    Possible vulnerability in F5 BIG-IP LTM - Improper input validation of the HTTP version number of the HTTP reqest allows any payload size and conent to pass through
    From : Eitan Caspi <eitanc () yahoo com>
    Date : Sun, 3 Jan 2016 21:10:27 +0000 (UTC)
    

    【讨论】:

    • 你能把实现这个的全部代码发给我吗?
    • @KarthikJ,用上面的逻辑替换for date_stamp in soup.em:
    • @Padriac,我收到一个 utf-8 编码错误。我可以通过将我的 print(x) 语句更改为 print(x.encode("utf-8") 来修复它。有没有更好的方法来转换编码?
    • @KarthikJ,你用的是python2还是3?
    • 您的默认编码是 cp1252,问题在于 cmd 多于 python。您可以尝试将代码页设置为支持 utf-8 的内容或坚持手动编码。我不使用 windows,但我知道 cmd 在处理 utf-8 时不是最好的,我建议安装 cygwin 或使用像 pycharm 这样有免费社区版的 ide
    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2016-01-29
    • 2016-01-10
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多