【问题标题】:scraping B in <span><span> flow text </span> B </span> using BeautifulSoup使用 BeautifulSoup 在 <span><span> 流文本 </span> B </span> 中抓取 B
【发布时间】:2020-04-08 09:46:11
【问题描述】:

我有以下 bs4 元素标签:

<span><span>some content</span> B</span>

字符串 B 的 len 未知(为简化起见,我将其命名为 B)

如何使用 beautifulSoup 提取 "b" ?或者我只是作为解决方案来提取文本,然后使用一些正则表达式技术

谢谢

编辑:完整代码

def get_doc_yakarouler(license_plate,url = 'https://www.yakarouler.com/car_search/immat?immat='):
    response = requests.get(url+license_plate)
    content = response.content 
    doc = BeautifulSoup(content,'html.parser')
    result = doc.span.text
    if 'identifié' in result :
        return doc
    else : 
        return f"La plaque {license_plate} n'est pas recensé sur yakarouler"

doc = get_doc_yakarouler('AA300AA')
span = doc.find_all('span')
motorisation_tag = span[1]

我要提取“1.6 TDI”

我使用以下方法找到了解决方案:motorisation_tag.text.replace(u'\xa0', ' ').split(' ')[1] 但我想直接使用 bs4 是否可行

【问题讨论】:

  • 你能分享一些代码吗?
  • 是的!完成了
  • @Doxcos44 看看下面的答案

标签: python html web-scraping beautifulsoup


【解决方案1】:

假设您有一个变量span 代表外部&lt;span&gt; 标记,您可以执行以下操作来提取“B”:span.contents[1]。这是因为.contents 将返回标签内容的列表,在本例中为[&lt;span&gt;some content&lt;/span&gt;, ' B']。然后您可以访问“B”文本作为数组的第二个元素。请注意,如果 B 之前有一个空格,就像您在 HTML 示例中显示的那样,该空格将包含在字符串中

【讨论】:

  • 谢谢!这么简单
【解决方案2】:
from bs4 import BeautifulSoup as bs , NavigableString
html = '<span><span>some content</span> B</span>'
soup = bs(html, 'html.parser')
span = soup.find("span")
# First approach Using Regular Expressions
outer_text_1 = span.find(text=True, recursive=False)
# Second approach is looping through the contents of the tag and check if it's the outer text and not a tag
outer_text_2 = ' '.join([t for t in span.contents if type(t)== NavigableString])

print(outer_text_1) # output B
print(outer_text_2) # output B

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多