【问题标题】:Python exclude certain image paths from Beautifulsoup webpage scrapePython从Beautifulsoup网页抓取中排除某些图像路径
【发布时间】:2021-04-22 16:24:01
【问题描述】:

我创建了以下 python 脚本来从指定的 url 中提取图像 src 路径:

from requests_html import HTMLSession
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests

url="https://www.example.com/"

session = HTMLSession()
r = session.get(url)

b  = requests.get(url)
soup = BeautifulSoup(b.text, "lxml") 

images = soup.find_all('img')
for img in images:
    if img.has_attr('src'):
        print(img['src'])

脚本运行良好,但我们使用 CDN,所以一些图像路径类似于:

https://i2.wp.com/www.example.com/wp-content/uploads/2020/06/image-name.png?fit=250%2C250&ssl=1 

所以,我希望能够排除某些以 https://i2.wp.com 开头的图像 src 路径(可能是正则表达式),例如:

url="https://www.example.com/"
exclude=".*https://i2.wp.com"

images = soup.find_all('img')
for img in images:
    if not ** something here to ignore excluded image src urls **:
        if img.has_attr('src'):
            print(img['src'])

这可能吗?

谢谢

【问题讨论】:

  • 拼写为.startswith(...),例如if img['src'].startswith("https://i2.wp.com/"): ...

标签: python beautifulsoup python-requests


【解决方案1】:

您可以使用正则表达式,或者只是按照说明使用.startswith()。然后在你的 for 循环中,如果它以此开头,continue。这意味着代码将停在那里并转到迭代中的下一项:

url="https://www.example.com/"
exclude="https://i2.wp.com"

images = soup.find_all('img')
for img in images:
    if img.has_attr('src'):
        if img['src'].startswith(exclude):
            continue
        print(img['src'])

【讨论】:

    【解决方案2】:

    就这么简单:

    url="https://www.example.com/"
    exclude=".*https://i2.wp.com"
    
    images = soup.find_all('img')
    for img in images:
        if img.has_attr('src') and not img["src"].startswith(exclude):
            print(img['src'])
    

    【讨论】:

      【解决方案3】:

      您可以使用属性=值选择器将各种要求(img 具有 src 但没有以特定字符串开头的 irc)绑定到一个衬里(无循环):

      images = [i['src'] for i in soup.select("img[src]:not([src^='https://i2.wp.com/'])")]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-25
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 2012-04-22
        • 1970-01-01
        相关资源
        最近更新 更多