网页抓取图像:找不到“rel”选择器

2024-05-02 17:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习自动化枯燥的东西的网页抓取部分的教程,并希望从https://swordscomic.com/中抓取图像

脚本应该1)下载并解析html 2)下载漫画图像3)点击“上一个漫画”按钮4)重复1-3

脚本可以下载第一个漫画,但在点击“上一个漫画”按钮或下载下一个漫画图像时会卡住

这方面可能存在的问题可能是:

Al的教程指示查找“rel”选择器,但我找不到它。我相信这个网站使用的格式与Al的教程指导的网站略有不同。我相信我使用了正确的选择器,但脚本仍然崩溃

这也可能是该网站的主页面包含漫画图像的方式,然后每个“先前”漫画都有一个额外的文件路径(以/CCCLXVIII/或其形式)

我试过:

在初始页面添加漫画版本,但这只会导致脚本更早崩溃

将脚本的“previous button”部分指向元素中的另一个选择器,但仍然会出现“索引超出范围”错误

以下是我的脚本:

#! python3
#swordscraper.py - Downloads all the swords comics.

import requests, os, bs4
os.chdir(r'C:\Users\bromp\OneDrive\Desktop\Python')
os.makedirs('swords', exist_ok=True) #store comics in /swords
url = 'https://swordscomic.com/' #starting url

while not url.endswith('#'):

 #Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status

soup = bs4.BeautifulSoup(res.text, 'html.parser') 

#Find the URL of the comic image.
comicElem = soup.select('#comic-image')
if comicElem == []:
    print('Could not find comic image.')
else:
    comicUrl = comicElem[0].get('src')
    comicUrl = "http://" + comicUrl
    if 'swords' not in comicUrl:
        comicUrl=comicUrl[:7]+'swordscomic.com/'+comicUrl[7:]
    #Download the image.
    print('Downloading image %s...' % (comicUrl))
    res = requests.get(comicUrl)
    res.raise_for_status()

#Save the image to ./swords
imageFile = open(os.path.join('swords', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
    imageFile.write(chunk)
imageFile.close()

#Get the Prev button's url.
prevLink = soup.select('a[id=navigation-previous]')[0]
url = 'https://swordscomic.com/' + prevLink.get('href')


print('Done')

以下是脚本执行的输出及其给出的特定错误消息:

Downloading page https://swordscomic.com/...
Downloading image http://swordscomic.com//media/Swords363bt.png...
Downloading page https://swordscomic.com//comic/CCCLXII/...
Could not find comic image.
Traceback (most recent call last):
  File "C:\...\", line 39, in <module>
    prevLink = soup.select('a[id=navigation-previous]')[0]
IndexError: list index out of range

Tags: thehttps图像image脚本comurlos
1条回答
网友
1楼 · 发布于 2024-05-02 17:15:08

页面是用JavaScript呈现的。特别是您提取的链接:

<a href="/comic/CCCLXII/" id="navigation-previous" class="navigation-button navigation-previous" onclick="COMICS.previousButtonPressed(); return false;"></a>

有一个onclick()事件,该事件可能链接到下一页。此外,该页面使用XHR。因此,您唯一的选择是使用呈现JavaScript的技术,因此请尝试使用Selenium或请求htmlhttps://github.com/psf/requests-html

相关问题 更多 >