【问题标题】:How to separate links of images on the basis of content inside them in beautifulsoup4如何根据beautifulsoup4中的内容来分离图像的链接
【发布时间】:2020-09-08 17:09:27
【问题描述】:

我是 BeautifulSoup4 的新手,我正在尝试从一个站点获取所有图片链接,例如 Unsplash,但我只想要在该 URL 中包含单词“照片”的 URL,例如。

https://images.unsplash.com/photo-1541892079-2475b9253785?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60

我不想要包含单词“profile”的网址,例如。

https://images.unsplash.com/profile-1508728808608-d3781b017e73?dpr=1&auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff

我该怎么做,我正在使用 Pyhton 3.6 和 urllib3。

【问题讨论】:

  • 您可以简单地获取它们,然后过滤掉您的代码中不需要的那些。
  • 你能添加一个带代码的例子吗,因为我是新手

标签: python web-scraping beautifulsoup


【解决方案1】:

你可以以这个脚本为例,如何过滤链接:

import requests
from bs4 import BeautifulSoup


url = 'https://unsplash.com'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for img in soup.find_all('img'):
    if 'photo' in img['src']:  # print only links with `photo` inside them
        print(img['src'])

打印:

https://images.unsplash.com/photo-1597649260558-e2bd7d35f043?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format%2Ccompress&fit=crop&w=1000&h=1000
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1598929214025-d6bb6167d43b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599567513879-604247ea2bd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80
https://images.unsplash.com/photo-1599366611308-719895c34512?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80

urllib:

import urllib.request
from bs4 import BeautifulSoup


url = 'https://unsplash.com'
soup = BeautifulSoup(urllib.request.urlopen(url).read(), 'html.parser')

for img in soup.find_all('img'):
    if 'photo' in img['src']:
        print(img['src'])

【讨论】:

  • 非常感谢 Andrej Kesely
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2019-10-13
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 2011-07-06
相关资源
最近更新 更多