python - 无法在 Python 中的 Beautiful Soup 中抓取 div 标签,
问题描述
我正在尝试下载官方网站上所有可用的口袋妖怪图像。我这样做的原因是因为我想要高质量的图像。以下是我编写的代码。
from bs4 import BeautifulSoup as bs4
import requests
request = requests.get('https://www.pokemon.com/us/pokedex/')
soup = bs4(request.text, 'html')
print(soup.findAll('div',{'class':'container pokedex'}))
输出是
[]
有什么我做错了吗?另外,从官方网站上抓取是否合法?有没有任何标签或什么可以说明这一点?谢谢
PS:我是 BS 和 html 的新手。
解决方案
图像是动态加载的,因此您必须使用selenium
它们来抓取它们。这是执行此操作的完整代码:
from selenium import webdriver
import time
import requests
driver = webdriver.Chrome()
driver.get('https://www.pokemon.com/us/pokedex/')
time.sleep(4)
li_tags = driver.find_elements_by_class_name('animating')[:-3]
li_num = 1
for li in li_tags:
img_link = li.find_element_by_xpath('.//img').get_attribute('src')
name = li.find_element_by_xpath(f'/html/body/div[4]/section[5]/ul/li[{li_num}]/div/h5').text
r = requests.get(img_link)
with open(f"D:\\{name}.png", "wb") as f:
f.write(r.content)
li_num += 1
driver.close()
输出:
12 个口袋妖怪图像。这是前2张图片:
图 1:
图 2:
另外,我注意到页面底部有一个加载更多按钮。单击时,它会加载更多图像。单击加载更多按钮后,我们必须继续向下滚动以加载更多图像。如果我没记错的话,网站上共有 893 张图片。为了抓取所有 893 图像,您可以使用以下代码:
from selenium import webdriver
import time
import requests
driver = webdriver.Chrome()
driver.get('https://www.pokemon.com/us/pokedex/')
time.sleep(3)
load_more = driver.find_element_by_xpath('//*[@id="loadMore"]')
driver.execute_script("arguments[0].click();",load_more)
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
lastCount = lenOfPage
time.sleep(1.5)
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
li_tags = driver.find_elements_by_class_name('animating')[:-3]
li_num = 1
for li in li_tags:
img_link = li.find_element_by_xpath('.//img').get_attribute('src')
name = li.find_element_by_xpath(f'/html/body/div[4]/section[5]/ul/li[{li_num}]/div/h5').text
r = requests.get(img_link)
with open(f"D:\\{name}.png", "wb") as f:
f.write(r.content)
li_num += 1
driver.close()
推荐阅读
- java - Hibernate AnnotationException:使用@OneToMany 或@ManyToMany 定位未映射的类
- object - 下拉列表未填充 Angular 中的 API 数据
- c++ - 浮点格式数组的平均值
- unit-testing - 为什么要进行单元测试?
- c# - 使用 USB 批量传输进行数据采集
- javascript - 使用 postgreSQL 和 express JS 处理 nodejs 中的迁移错误
- android - 服务器上的数据更改时如何自动获取数据更改
- django - Django UniqueConstraint 不适用
- php - PHP,有什么方法可以调试 ftp_put()?
- c# - C# 二进制 PSCmdLet | 如果使用某个其他参数,则停用参数