【问题标题】:How to isolate part of a link in BS4?如何隔离BS4中的部分链接?
【发布时间】:2020-09-11 04:50:28
【问题描述】:

作为一个入门项目,我使用 BS4 来识别使用 WordPress 的网站。

我无法正确获取标识符。我知道 WordPress 网站在 html 中有 /wp-content/ 链接。但我没有正确隔离它们。

以下是一些链接示例:

img src="https://variety.com/wp-content/...
href="https://variety.com/wp-content/...

我一直在玩很多变化:

find_wordpress = soup.find('a', href = "wp-content")

但我没有做对。域会改变,所以我只需要隔离 /wp-content/ 部分。

有什么建议吗?谢谢!

【问题讨论】:

  • 你必须使用regex或使用"wp-content" in href的函数
  • 如果您需要所有链接,请使用find_all
  • 如果你只想识别WordPress,那么也许你应该使用if "wp-content" in html而不使用BS4
  • 嗨@furas 这是一个有趣的想法!我虽然需要 BS4 才能打开并查看 html。还有其他方法吗?
  • html 是一个字符串,您可以使用字符串函数或正则表达式 - 但如果您需要更复杂的东西,那么 BS4lxml 更有用。有时BS4 可能更有用,因为它可以使用正则表达式或函数来过滤项目。

标签: python web-scraping beautifulsoup scrapy


【解决方案1】:

如果你只识别WordPress那么也许你可以使用

"/wp-content/" in html

但如果在其他文本中使用/wp-content/,有时可能会产生误导。


html = '''<a href="http://one.com/wp-content/1"></a>'''

result = ('/wp-content/' in html1)
print('result 1:', result)

html = '''<a href="http://one.com/2"></a>'''

result = ('/wp-content/' in html)
print('result 2:', result)

如果你需要检查href,那么你可以使用regex

soup.find('a', href=re.compile(r'.*/wp-content/.*'))

甚至

soup.find('a', href=re.compile(r'/wp-content/'))

或者你可以使用函数

def test_link(link):
    return '/wp-content/' in link

result = soup.find('a', href=test_link)

或与lambda相同

soup.find('a', href=lambda link:'/wp-content/' in link)

from bs4 import BeautifulSoup

html1 = '''<a href="http://one.com/wp-content/1"></a>'''
html2 = '''<a href="http://one.com/2"></a>'''

result = ('/wp-content/' in html1)
print('1:', result)

result = ('/wp-content/' in html2)
print('2:', result)


soup1 = BeautifulSoup(html1, 'lxml')
soup2 = BeautifulSoup(html2, 'lxml')

import re

result = soup1.find('a', href=re.compile(r'/wp-content/'))
print('1:', result, '-->', (result is not None))
result = soup2.find('a', href=re.compile(r'/wp-content/'))
print('2:', result, '-->', (result is not None))

#def test(link):
#    return '/wp-content/' in link

result = soup1.find('a', href=lambda link:'/wp-content/' in link)
print('1:', result, '-->', (result is not None))
result = soup2.find('a', href=lambda link:'/wp-content/' in link) 
print('2:', result, '-->', (result is not None))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 2023-01-30
    • 2022-08-20
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多