【发布时间】:2021-04-06 15:38:11
【问题描述】:
我正在通过请求和 bs4 抓取以下网络漫画网站以下载漫画图片:www.qwantz.com
在浏览器检查器中,当我选择 webcomic 元素并复制 CSS 选择器时,我得到以下信息:
comicElem = soup.select('body > center > table > tbody > tr > td:nth-child(2) > img')
查看网站的 html,这是有道理的。该部分中的元素是这样对齐的:
.\
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<tr>
.\
但是,此选择器返回一个空列表。当我将选择器备份到 (... > td') 时,我在选择器对象中获得了三个同级元素。
对于我尝试 1 - 2 的每个数字参数,以下所有结果也会产生空列表:
comicElem = soup.select('body > center > table > tbody > tr > td:nth-child(1)')
comicElem = soup.select('body > center > table > tbody > tr > td')[1]
使用comicElem = soup.select('body > center > table > tbody > tr > td > td > img') 可以获得我想要的结果。但我想知道这里发生了什么导致从网络检查器复制的 CSS 选择器失败。简而言之,我希望我的代码使用从浏览器检查器复制的 CSS 选择器工作。例如td:nth-child(2)。
供参考,以下是相关代码:
#! python3
# scheduledWebComicDL.py - Downloads comics but first checks if there is
# an update before
import requests, os, bs4, threading
folderName = 'Web Comics'
os.makedirs(folderName, exist_ok=True) # store comics in folderName
def downloadQwantz():
# Web comic site to parse.
site = 'http://www.qwantz.com'
# Make the soup with requests & bs4.
res = requests.get(site)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Get image url.
comicElem = soup.select('body > center > table > tbody > tr > td > td > img')
comicUrlShort = comicElem[0].get('src')
comicUrl = site + '/' + comicUrlShort
# Confirm that there is an img url.
if comicElem == 0:
print('Could not find comic element at %s.' % (site))
# Begin download of img with url.
else:
checkAndDownload(comicUrl)
downloadQwantz()
【问题讨论】:
-
你能提供完整的代码来重现这个错误吗?
-
已提供完整代码,以及更具体的我想要实现的目标。
-
我已经投票决定重新开放。我认为您只需要与 downloadQwant() 相关的代码,您可以将其简化为仅几行来演示问题。可能是错误的 html 导致解析器出错。
-
感谢您的反馈。对此相对较新。
标签: python css beautifulsoup css-selectors