gpt4 book ai didi

javascript - 具有点击按钮的网页抓取网站

转载 作者:行者123 更新时间:2023-12-02 23:38:49 24 4
gpt4 key购买 nike

我正在尝试抓取一个具有多个 javascript 渲染页面的网站 ( https://openlibrary.ecampusontario.ca/catalogue/ )。我能够从第一页获取内容,但我不确定如何让我的脚本单击后续页面上的按钮来获取该内容。这是我的脚本。

import time
from bs4 import BeautifulSoup as soup
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

# The path to where you have your chrome webdriver stored:
webdriver_path = '/Users/rawlins/Downloads/chromedriver'

# Add arguments telling Selenium to not actually open a window
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920x1080')

# Fire up the headless browser
browser = webdriver.Chrome(executable_path = webdriver_path,
chrome_options = chrome_options)

# Load webpage
url = "https://openlibrary.ecampusontario.ca/catalogue/"
browser.get(url)

# to ensure that the page has loaded completely.
time.sleep(3)

data = []

# Parse HTML, close browser
page_soup = soup(browser.page_source, 'lxml')
containers = page_soup.findAll("div", {"class":"result-item tooltip"})

for container in containers:
item = {}
item['type'] = "Textbook"
item['title'] = container.find('h4', {'class' : 'textbook-title'}).text.strip()
item['author'] = container.find('p', {'class' : 'textbook-authors'}).text.strip()
item['link'] = "https://openlibrary.ecampusontario.ca/catalogue/" + container.find('h4', {'class' : 'textbook-title'}).a["href"]
item['source'] = "eCampus Ontario"
item['base_url'] = "https://openlibrary.ecampusontario.ca/catalogue/"
data.append(item) # add the item to the list

with open("js-webscrape-2.json", "w") as writeJSON:
json.dump(data, writeJSON, ensure_ascii=False)

browser.quit()

最佳答案

您不必实际单击任何按钮。例如,要搜索带有关键字“电力”的项目,您可以导航到网址

https://openlibrary-repo.ecampusontario.ca/rest/filtered-items?query_field%5B%5D=*&query_op%5B%5D=matches&query_val%5B%5D=(%3Fi)electricity&filters=is_not_withdrawn&offset=0&limit=10000

这将返回一个 json 项目字符串,第一个项目是:

{"items":[{"uuid":"6af61402-b0ec-40b1-ace2-1aa674c2de9f","name":"Introduction to Electricity, Magnetism, and Circuits","handle":"123456789/579","type":"item","expand":["metadata","parentCollection","parentCollectionList","parentCommunityList","bitstreams","all"],"lastModified":"2019-05-09 15:51:06.91","parentCollection":null,"parentCollectionList":null,"parentCommunityList":null,"bitstreams":null,"withdrawn":"false","archived":"true","link":"/rest/items/6af61402-b0ec-40b1-ace2-1aa674c2de9f","metadata":null}, ...

现在,要获取该项目,您可以使用它的 uuid,然后导航到:

https://openlibrary.ecampusontario.ca/catalogue/item/?id=6af61402-b0ec-40b1-ace2-1aa674c2de9f

您可以像这样继续与该网站进行任何交互(这并不总是适用于所有网站,但它适用于您的网站)。

要找出当您单击某某按钮或输入文本时导航到的网址(我对上述网址所做的操作),您可以使用 fiddler

关于javascript - 具有点击按钮的网页抓取网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56175902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com