【问题标题】:How can I filter off thumbnails attachments in beautifulsoup?如何在 beautifulsoup 中过滤掉缩略图附件?
【发布时间】:2019-04-16 14:28:04
【问题描述】:

我早些时候写了一个 BeautifulSoup 脚本来抓取一个论坛的图片,它从第二页开始运行良好。第一页有几篇文章,附有一些jpeg文件的缩略图,但它不是有效的下载链接。

我没有对代码进行太多尝试,所以我只是从第 2 页开始抓取。但我还是想从第一页开始。

import requests
import bs4
import re

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                  'AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/73.0.3683.105 Safari/537.36 Vivaldi/2.4.1488.38'
}
url = "http://www.sechongse.com/forum/thread-10106367-1-1.html"
response = requests.get(url, headers=headers).content
soup = bs4.BeautifulSoup(response, 'html.parser')
soup_imgs = soup.find(name='div', attrs={'class':'t_msgfont'})\
        .find_all('img', alt="", src=re.compile(".jpg"))
for i, img in enumerate(soup_imgs, 1):
    src = img['src']
    print(src)

DOM

attachments/month_1809/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg
attachments/month_1809/20180920_c9f7ee5420e277ade049cdwQ7n5sQ3Nj.jpg
attachments/month_1809/20180920_111cbfcd81acbe556bceI8ZZluQ7mwvY.jpg
attachments/month_1809/20180920_e94dafd7c8b1ca99c1035YS0TnpdUCHO.jpg

Process finished with exit code 0

这样的帖子很容易在我的脚本中找到,但是,我无法摆脱这些附件,那么我该如何解决呢?有什么方法吗?回复?

【问题讨论】:

  • 类似的东西:是的,我想要 .jpeg 文件,但不是附件....jpeg。 |||或者我想要那些以 http(s) 开头的 jpeg,我可以下载到我的硬盘。

标签: python-3.x beautifulsoup python-requests


【解决方案1】:

这是用 Beautiful Soup 4.7+ 完成的。

似乎 CSS 选择器在这一点上可能对你很有效。这里我们检查 src 是否以.jpg 结尾,但不是以attachments 开头。我们可以使用$= 来测试属性的结束,^= 来测试开始:

import bs4

html = """
<img src="attachments/month_1809/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg"/>
<img src="some/other/image/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg"/>
"""

soup = bs4.BeautifulSoup(html, 'html.parser')
for img in soup.select('img[src$=".jpg"]:not([src^=attachments])'):
    src = img['src']
    print(src)

输出

some/other/image/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg

对于那些不喜欢使用选择器的人

import bs4
import re

html = """
<img src="attachments/month_1809/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg"/>
<img src="some/other/image/20180920_97a05cfc4ae8f0950356vcm54UmZbB5C.jpg"/>
"""

soup = bs4.BeautifulSoup(html, 'html.parser')
for img in soup.find_all('img', src=re.compile('^(?!attachments).*\.jpg$')):
    src = img['src']
    print(src)

【讨论】:

  • 我从朋友那里找到了这个,也很匹配。 src=re.compile("(http.*?jpg)", re.S)
  • 我会将您的帮助也写在我的脚本中用于学习目的,谢谢楼主!
  • 是的,通常有多种方法可以完成工作,很高兴你能成功。
猜你喜欢
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 2014-09-08
  • 2023-04-02
  • 1970-01-01
  • 2013-03-05
相关资源
最近更新 更多