python - 在 python 中使用 BeautifulSoup 搜索“a”链接中的图像
问题描述
我想获取所有<a href=''>
包含图像的内容(jpg、png、jpeg)
首先我发现我可以用这个 Beautifulsoup 代码下载链接
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
但我得到了我只想得到图像的所有字符串。
from bs4 import BeautifulSoup
import requests
import re
url = requests.get("https://8ch.net/a/res/869528.html")
soup = BeautifulSoup(url.text,"html.parser")
print soup
for a in soup.find_all(re.compile('([-\w]+\.(?:jpg|jpeg|png))') ):#'a', href=True):
print "Found the URL:", a #['href']
之后我发现我可以使用正则表达式来查找包含链接的所有链接。
我做错了什么?
解决方案
我刚刚完成了你想做的事情。我将用注释描述代码的用法。
from bs4 import BeautifulSoup
import requests
import re
url = requests.get("https://8ch.net/a/res/869528.html")
soup = BeautifulSoup(url.text,"html.parser")
for a in soup.find_all("a" , href=True):
if re.findall(r".+(?=jpg|png|jpeg)",a['href']):
# find out if the url contain jpg or png or jpeg , if not return a empty list. empty list is False
print(a['href'])