【问题标题】:Regex Search after a variable length text可变长度文本后的正则表达式搜索
【发布时间】:2015-11-17 19:42:29
【问题描述】:

我需要正则表达式来从以下标签中提取文本: 我正在使用 Python 和 BeautifulSoup

    <h4 style="color:#000000; line-height:20px; font-size:18px; margin-left:22px;
 overflow:auto; content:inherit; padding:10px; font-family:"Book Antiqua", 
Palatino, serif;">THE TEXT TO BE EXTRACTED IS HERE</h4></div><br /></div>

我尝试了以下方法:

stylecontent = 'color:#000000; line-height:20px; font-size:18px; margin-left:22px;
     overflow:auto; content:inherit; padding:10px; font-family:"Book Antiqua", 
    Palatino, serif;'

soup = BeautifulSoup(br.response().read(), "lxml")

scrap_soup = soup.findAll('h4', {'style': stylecontent})

但它并不总是有效,因为网站不断变化stylecontent。 现在我想使用正则表达式:

soup.find_all(re.compile("some_foo_regex")):

我对那个some_foo_regex很感兴趣。

谢谢。

【问题讨论】:

  • 您使用什么工具/语言?顺便说一句,这个 HTML 不正确(看引号)
  • 查看您使用的语言存在哪些 HTML 解析器。 HTML 和正则表达式不能很好地结合在一起。
  • 我投票决定将此问题作为离题结束,因为它是一个正则表达式问题,并且 OP 没有精确任何工具、语言或正则表达式风格。
  • 请出示您的beautifulsoup相关代码。

标签: python regex web-scraping beautifulsoup


【解决方案1】:

你可能会得到所有h4标签只有一个属性style

h4_tags = soup.find_all('h4', attrs = {'style' : True}) # Get all H4 tags with style attribute
for result in h4_tags:
    if len(result.attrs) == 1:                          # Print if it is the only attribute
        print result.contents                           # Print tag text contents

【讨论】:

  • 有没有办法从这些标签中获取文本?此外,我的投票也不起作用,因为我需要至少 15 名声望。顺便说一句,我还得到了具有其他标签的标签,包括样式。
  • result.contents 不打印内容吗?顺便说一句,你现在有 15 个代表 :) 另外,lambda 解决方案怎么样:h4_list = soup.find_all(lambda tag:tag.name == "h4" and len(tag.attrs) == 1 and tag["style"]) \n for result in h4_list: \n print result.contents?
  • h4_tags = soup.find_all('h4', attrs = {'style' : True}) 为我提供了我需要的所有标签和一些额外的标签,但运行该循环只会给我一个结果。
  • 这给了我一个KeyError: 'style'
  • 感谢告知。
猜你喜欢
  • 2013-06-22
  • 2018-06-24
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多