使用python中的BeautifulSoup搜索'a'链接中的图像

时间:2018-10-16 00:29:17

标签: python beautifulsoup

我想获取所有包含图像(jpg,png,jpeg)的<a href=''>

首先,我发现可以下载带有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']

之后,我发现可以使用正则表达式来查找包含链接的所有链接。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我认为regex在这里有点矫kill过正。只需检查最右边的点后的值即可。

from bs4 import BeautifulSoup
import requests

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 a["href"][a["href"].rfind(".")+1:] in ["jpeg", "png", "jpg"]:
        print(a["href"])

答案 1 :(得分:0)

我刚完成你想做的事。我将在注释中描述代码的用法。

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'])