我正在尝试使用beautifulsoup HTML解析器从网站上抓取图像。
该站点上的每个图像都有2种图像标签。一个用于缩略图,另一个用于较大尺寸的图像,该图像仅在单击缩略图并展开后才会显示。较大的标签包含class =“ expanded-image”属性。
我正在尝试通过HTML进行解析,并获取包含图像源的扩展图像的“ src”属性。
当我尝试执行代码时,什么也没有发生。它只是说过程完成了,没有刮任何图像。但是,当我不尝试过滤代码并仅将tag作为参数时,它将下载所有缩略图。
这是我的代码:
import webbrowser, requests, os
from bs4 import BeautifulSoup
def getdata(url):
r = requests.get(url)
return r.text
htmldata = getdata('https://boards.4chan.org/a/thread/30814')
soup = BeautifulSoup(htmldata, 'html.parser')
list = []
for i in soup.find_all("img",{"class":"expanded-thumb"}):
list.append(i['src'].replace("//","https://"))
def download(url, pathname):
if not os.path.isdir(pathname):
os.makedirs(pathname)
filename = os.path.join(pathname, url.split("/")[-1])
response = requests.get(url, stream=True)
with open(filename, "wb") as f:
f.write(response.content)
for a in list:
download(a,"file")
使用“列表”作为变量名可能会遇到问题。这是python中的一种类型。从此开始(用所需的任何线程替换TEST_4CHAN_URL),并结合上面注释中的建议。
import requests
from bs4 import BeautifulSoup
TEST_4CHAN_URL = "https://boards.4chan.org/a/thread/<INSERT_THREAD_ID_HERE>"
def getdata(url):
r = requests.get(url)
return r.text
htmldata = getdata(TEST_4CHAN_URL)
soup = BeautifulSoup(htmldata, "html.parser")
src_list = []
for i in soup.find_all("a", {"class":"fileThumb"}):
src_list.append(i['href'].replace("//", "https://"))
print(src_list)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句