【问题标题】:Python - Find the correct link within a post with a wildcardPython - 在带有通配符的帖子中找到正确的链接
【发布时间】:2020-01-30 18:54:58
【问题描述】:

我尝试使用以下 python 代码从论坛中提取链接。该帖子包含很多html链接,我尝试找到一个特殊的:

<a href="https://site.html" target="_blank" class="externalLink" rel="nofollow">Daily news <img src="https://site.html/pic.png" class="bbCodeImage LbImage" alt="[​IMG]" data-url="https://site.html/pic.png"></a>

这是我的代码:

from bs4 import BeautifulSoup
import defs
import re

def find_link(soup ,date, section, URL):
    #Find the right post
    section = soup.find('li', {"data-author":"Ghostwriter"})
    #Search the link inside the post
    link = section.find(string=" Daily news ")
    #Mark the whole html section
    section_new = str(link.find_parents('a'))
    #get the link
    link_new = re.search("(?P<url>https?://[^\s]+)", section_new).group("url")

现在的问题是,有时“每日新闻”之前或之后没有空格,而我的代码失败了:

AttributeError: 'NoneType' object has no attribute 'find_parents'

如何使我的代码更灵活,例如使用一些通配符。例如:

link = section.find(string="*Daily news*")

非常感谢!

【问题讨论】:

    标签: python hyperlink wildcard forum


    【解决方案1】:

    我相信您可以使用re.compile 作为string 的参数。这应该允许您创建一个匹配您正在寻找的字符串的正则表达式。更多关于 python 正则表达式的信息可以在这里找到:https://docs.python.org/3/library/re.html

    【讨论】:

    • 谢谢!这对我有用:link = section.find(text=re.compile('Daily news'))
    【解决方案2】:

    尝试使用 tags.get 返回一个字符串,那么你应该能够使用 str.statswith 来做你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      相关资源
      最近更新 更多