【问题标题】:How to substract soup.find_all() in python 3如何在python 3中减去soup.find_all()
【发布时间】:2016-11-28 02:46:12
【问题描述】:

我想更改我的soup.find.all 的输出。在原始来源中,我们有这个:

<a href="/book/nfo/?id=4756888" class="ajax nfo"></a>

我的soup.find_all:

href = [b.get('href') for b in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))]

给我这个:

/book/nfo/?id=4756888

但我想要这个:

http://127.0.0.1/book/download/?id=4756888

【问题讨论】:

  • 这是您想用下载替换 nfo 的单个 url /book/nfo/ 吗?
  • 还有多少其他的url?
  • 我还有很多其他的任何 url。
  • 您必须列出所有 url 以获得解决方案,或者至少列出它们都遵循的通用模式。但是通过阅读以下答案,您可能已经了解了如何解决。
  • Mohammad Yusuf Ghazi 的解决方案为我工作。

标签: python regex beautifulsoup


【解决方案1】:

您可以使用Python string 的属性向其中添加和替换部分:

a='/book/nfo/?id=4756888'
b = 'http://127.0.0.1' + a.replace('nfo', 'download')
print(b)

给出:

'http://127.0.0.1/book/download/?id=4756888'

这里不需要使用regex

【讨论】:

  • 你是对的。但我确信他会带来更多的网址:)
【解决方案2】:

您可以编译正则表达式并将其应用到列表推导中,如下所示:

from bs4 import BeautifulSoup
import re

soup = BeautifulSoup('<a href="/book/nfo/?id=4756888" class="ajax nfo"></a>', 'html.parser')
re_s = re.compile(r'(.*?\/)nfo(\/.*?)').sub
hrefs = [re_s('http://127.0.0.1' + r'\1download\2', a.get('href')) for a in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))]
print(hrefs)

给你:

['http://127.0.0.1/book/download/?id=4756888']

【讨论】:

    【解决方案3】:

    您可以在前面加上http://127.0.0.1,并使用python的re.sub()函数将'nfo'替换为'download'。

    re.sub(r'pattern_to_match',r'replacement_string', string)
    

    你可以如下实现:

    from bs4 import BeautifulSoup
    import re
    
    soup = BeautifulSoup("""<a href="/book/nfo/?id=4756888" class="ajax nfo"></a>""")
    c = ['http://127.0.0.1'+b.get('href') for b in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))]
    print([re.sub(r'nfo',r'download',q) for q in c ])
    

    输出:

    ['http://127.0.0.1/book/download/?id=4756888']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2022-01-10
      • 2011-02-21
      • 1970-01-01
      相关资源
      最近更新 更多