【发布时间】: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