使用相同的分页链接刮取分页

2024-09-28 03:17:55 发布

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

我正试图从这个链接中获取股票信息:https://www.affarsvarlden.se/bors/kurslistor/stockholm-large/kurs/

在python中,它可以很好地使用requests处理前100行,但是剩余的行隐藏在pagination元素下。问题是我怎样才能得到这些。困难的是,第二个页面(包含剩余行)的链接与第一个页面的链接相同,并且在“开发人员工具”的“网络”选项卡中查看时,在这两个页面之间进行更改时,我看不到有任何请求。有没有办法使用requests模块来实现这一点,或者我需要使用类似selenium的东西?我也不能让后者工作

我非常感谢您的任何意见


Tags: https信息链接www页面requests股票large
2条回答

你可以用硒来做这个。下面的脚本将打开网页并转到下一页

import selenium
from selenium import webdriver

driver = webdriver.Chrome()

# navigate to webpage
driver.get('https://www.affarsvarlden.se/bors/kurslistor/stockholm-large/kurs/')

# next button path
next_button = driver.find_element_by_xpath('//*[@id="canvas"]/div[2]/div/div[2]/div/div/div[3]/div[2]/div/div/div[2]/ul/li[4]/a')

# Clicking button throws error the fist time
try:
    next_button.click()
    pass
except Exception:
    next_button.click()

编辑:您的工作目录中需要chromedriver.exe才能使用webdriver

据我所知,所有的数据已经上传到页面时,请求页面。所以,你可以试试这个

from bs4 import BeautifulSoup
from pandas.io.json import json_normalize
import requests
import json

url = 'https://www.affarsvarlden.se/bors/kurslistor/stockholm-large/kurs/'
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'html.parser')

for tag in soup.findAll('script'):
    content = tag.get_text()

    if '__INITIAL_STATE__' not in content:
        continue

    index = content.find('{')
    data = json.loads(content[index:])
    df = json_normalize(data['stocklist']['stockholm-large/kurs/'], 'info')

相关问题 更多 >

    热门问题