【发布时间】:2021-05-25 03:47:54
【问题描述】:
我正在抓取一个使用 javascript 动态呈现的网站。点击> 按钮时,网址不会改变所以我一直在尝试查看网络部分的检查器,更具体地说是“请求网址”和“请求方法”的“常规”部分以及在“表单数据”部分中寻找可以唯一区分每个连续页面的任何类型的 ID。但是,当记录从页面到页面单击> 按钮的日志时,“表单数据”数据似乎每次都相同(参见图片):
目前我的代码没有包含此方法,因为在“表单数据”部分找到唯一标识符之前,我看不到它的帮助。但是,如果有帮助,我可以显示我的代码。本质上,它只是在我的 while 循环中一遍又一遍地提取数据的第一页,即使我在尝试使用 BeautifulSoup 获取数据之前使用的是带有 selenium 的驱动程序并使用driver.find_elements_by_xpath("xpath of > button").click()。
(更新代码见 cmets)
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import pandas as pd
from pandas import *
masters_list = []
def extract_info(html_source):
# html_source will be inner HTMl of table
global lst
soup = BeautifulSoup(html_source, 'html.parser')
lst = soup.find('tbody').find_all('tr')[0]
masters_list.append(lst)
# i am printing just id because it's id set as crypto name you have to do more scraping to get more info
chrome_driver_path = '/Users/Justin/Desktop/Python/chromedriver'
driver = webdriver.Chrome(executable_path=chrome_driver_path)
url = 'https://cryptoli.st/lists/fixed-supply'
driver.get(url)
loop = True
while loop: # loop for extrcting all 120 pages
crypto_table = driver.find_element(By.ID, 'DataTables_Table_0').get_attribute(
'innerHTML') # this is for crypto data table
extract_info(crypto_table)
paginate = driver.find_element(
By.ID, "DataTables_Table_0_paginate") # all table pagination
pages_list = paginate.find_elements(By.TAG_NAME, 'li')
# we clicking on next arrow sign at last not on 2,3,.. etc anchor link
next_page_link = pages_list[-1].find_element(By.TAG_NAME, 'a')
# checking is there next page available
if "disabled" in next_page_link.get_attribute('class'):
loop = False
pages_list[-1].click() # if there next page available then click on it
df = pd.DataFrame(masters_list)
print(df)
df.to_csv("crypto_list.csv")
driver.quit()
【问题讨论】:
-
可能是当您单击按钮时没有发出任何请求,这就是为什么它没有改变任何值,按钮在 html 中显示隐藏的东西,请参阅网络中 url 的响应
-
感谢您的提示!你能引导我到我在网络中看到 URL 响应的地方吗?上面的截图中显示了吗?当我运行代码时,它会启动浏览器,我可以看到它从一页点击到下一页,直到它用完导致驱动程序退出。它只是一遍又一遍地返回第一页。
-
是的,如上图所示,您可以分享一些代码,方便其他人解决。
-
好的,刚刚更新了代码。我不明白“html 中的隐藏内容”在哪里。你能解释一下它们的含义吗?
-
实际上隐藏是错误的词,我的意思是通过 javascript 或 css 隐藏的东西。我可以问一下 url 和你想抓取的东西吗
标签: python selenium-webdriver post web-scraping