使用 python beautiful soup 从 oreilly media 网站提取书名

Extract book names from oreilly media site using python beautiful soup

我正在尝试使用 python beautiful soup 从 oreilly media 网站提取书名。

但是我看到书名不在页面源代码中 html。

我正在用这个link看书:

https://www.oreilly.com/search/?query=*&extended_publisher_data=true&highlight=true&include_assessments=false&include_case_studies=true&include_courses=true&include_playlists=true&include_collections=true&include_notebooks=true&include_sandboxes=true&include_scenarios=true&is_academic_institution_account=false&source=user&formats=book&formats=article&formats=journal&sort=date_added&facet_json=true&json_facets=true&page=0&include_facets=true&include_practice_exams=true

随附的屏幕截图显示了包含前两本书的网页以及 chrome 开发人员工具,箭头指向我要提取的元素。

我查看了页面源但找不到书名 - 也许它们隐藏在主要 html.

中的其他 link 中

我试图打开 html 中的一些 link 并搜索书名,但找不到任何东西。

能不能用美汤从网站上提取出第一或第二本书的名字? 如果没有,还有其他 python 软件包可以做到吗?也许是硒?

或者作为最后的手段,任何其他工具...

因此,如果您调查网络选项卡,在加载页面时,您正在向 API 发送请求

它returnsjson有书。

经过我的调查,您可以通过

获取您的标题
import json

import requests

response_json = json.loads(requests.get(
    "https://www.oreilly.com/api/v2/search/?query=*&extended_publisher_data=true&highlight=true&include_assessments=false&include_case_studies=true&include_courses=true&include_playlists=true&include_collections=true&include_notebooks=true&include_sandboxes=true&include_scenarios=true&is_academic_institution_account=false&source=user&formats=book&formats=article&formats=journal&sort=date_added&facet_json=true&json_facets=true&page=0&include_facets=true&include_practice_exams=true&orm-service=search-frontend").text)

for book in response_json['results']:
    print(book['highlights']['title'][0])

要解决这个问题你需要知道美汤可以对付使用计划html的网站。因此,在其页面中使用 JavaScript 的网站 beautiful soup 无法获取您正在寻找的所有页面数据 bcz 您需要一个喜欢在网站中加载 JavaScript 数据的浏览器。 在这里你需要使用 Selenium bcz 它打开浏览器页面并加载页面的所有数据,你可以像这样将两者结合使用:

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import lxml

# This will make selenium run in backround
chrome_options = Options()
chrome_options.add_argument("--headless")

# You need to install driver
driver = webdriver.Chrome('#Dir of the driver' ,options=chrome_options)
driver.get('#url')
html = driver.page_source
soup = BeautifulSoup(html, 'lxml')

有了这个你就可以得到你需要的所有数据,别忘了 写在最后以在后台退出 selenium。

driver.quit()