无法使用请求从网页中获取某些字段

SMT*_*MTH 1 python web-scraping python-3.x python-requests

我正在尝试使用模块从这个网页中获取不同容器的标题和链接requests,但我找不到任何方法来做到这一点。我试图找到任何通常出现在开发工具中的隐藏 API,但我失败了。我注意到在不同的时候,动态生成的内容大部分时间都在某些脚本标签中可用。但是,在这种情况下,我也找不到其中的内容。作为最后的手段,我使用 Selenium 来获取它们。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

link = 'https://www.firmy.cz/kraj-praha?q=prodej+kol'

def get_content(url):
    driver.get(url)
    for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'.companyDetail'))):
        item_link = item.find_element_by_css_selector("h3 > a.companyTitle").get_attribute("href")
        item_title = item.find_element_by_css_selector("span.title").text
        yield item_link,item_title

if __name__ == '__main__':
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver,10)
        for item in get_content(link):
            print(item)
Run Code Online (Sandbox Code Playgroud)

脚本产生的结果如下:

('https://www.firmy.cz/detail/12824790-bike-gallery-s-r-o-praha-vokovice.html', 'Bike Gallery s.r.o.')
('https://www.firmy.cz/detail/13162651-bikeprodejna-cz-praha-dolni-chabry.html', 'BIKEPRODEJNA.CZ')
('https://www.firmy.cz/detail/406369-bikestore-cz-praha-podoli.html', 'Bikestore.cz')
('https://www.firmy.cz/detail/12764331-shopbike-cz-praha-ujezd-nad-lesy.html', 'Shopbike.cz')
Run Code Online (Sandbox Code Playgroud)

如何使用请求模块获取相同的结果?

Kat*_*ova 6

分析了原始页面源后,解决方案似乎非常简单 - 您必须_escaped_fragment_=在链接中附加一个额外的URL 参数。例如,获取所需内容的简单 Python 脚本可以如下所示:

import requests
r = requests.get('https://www.firmy.cz/kraj-praha?q=prodej+kol&_escaped_fragment_=')
print (r.content)
Run Code Online (Sandbox Code Playgroud)

下面的 Python 脚本使用requests和解析接收到的响应来模拟您当前的实现:

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

base = 'https://www.firmy.cz'
link = 'https://www.firmy.cz/kraj-praha?q=prodej+kol&_escaped_fragment_='

def get_info(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    for item in soup.select(".companyDetail"):
        item_link = urljoin(base,item.select_one("h3 > a.companyTitle")['href'])
        item_title = item.select_one("span.title").get_text(strip=True)
        yield item_link,item_title

if __name__ == '__main__':
    for item in get_info(link):
        print(item)
Run Code Online (Sandbox Code Playgroud)

在执行之前,请确保您已通过在 中运行以下命令来安装所需的库cmd

pip install bs4
pip install html5lib
pip install lxml
Run Code Online (Sandbox Code Playgroud)

  • 不客气,@SMTH。该链接在元标记中定义:`<meta http-equiv="refresh" content="0;url=/kraj-praha?q=prodej+kol&_escaped_fragment_=" />` (2认同)