【问题标题】:BeautifulSoup only identifies 5 out of 25 entriesBeautifulSoup 仅识别出 25 个条目中的 5 个
【发布时间】:2021-03-26 21:26:10
【问题描述】:

我正在尝试在每页显示 25 个条目的零售网站上收集有关二手车的数据(型号、公里数、价格)。它适用于前 5 个条目,但随后它停止并且不从其余 20 个条目中收集数据。所有 25 个条目的标签都是相同的,所以我不明白为什么它在 5 之后停止。感谢您的帮助!

import requests
from bs4 import BeautifulSoup


counter=0
    

page = requests.get('https://www.willhaben.at/iad/gebrauchtwagen/auto/ford-gebrauchtwagen/mustang')
soup = BeautifulSoup(page.content, 'html.parser')

for Inhalt_1 in soup.find_all('div', class_='Box-wfmb7k-0 hkyQgZ'):
    print(Inhalt_1.h3.text)
print()
for Inhalt_2 in soup.find_all('span', class_='Text-sc-10o2fdq-0 fiVXiu'):
    print(Inhalt_2.text)
print()    
for Inhalt_3 in soup.find_all('div', class_='Text-sc-10o2fdq-0 fTyYiu'):
    if (counter+1)%2==0:
        print(Inhalt_3.span.text, 'km')
    counter +=1

输出:

Ford Mustang Cabrio 2,3 Turbo Ecoboost 317 Ps Autom Leder Klima
Ford Mustang V6
Ford Mustang 5,0 Ti-VCT V8 GT
Ford Mustang Shelby GT500
Ford Mustang Ford Mustang Mach I Coupe

€ 32.900
€ 16.500
€ 32.500
€ 79.800
€ 49.500

77.900 km
113.000 km
111.000 km
21.879 km
100.000 km

【问题讨论】:

  • 我假设网站一开始只加载 5 个元素,并在使用滚动到页面底部时填充它们。

标签: python-3.x beautifulsoup


【解决方案1】:

感谢@Bijay Regmi 的提示。事实上,除非向下滚动,否则该网站只会加载上部。要自动执行此操作,可以使用例如selenium webdriver 向下滚动整个网页(如果你立即跳转到网站底部,中间部分将不会加载)。这是解决方案。

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time


counter=0
Y=1080
    

page= "https://www.willhaben.at/iad/gebrauchtwagen/auto/ford-gebrauchtwagen/mustang"
PATH = "/Applications/chromedriver"
driver = webdriver.Chrome(PATH)
    
driver.get(page)

for i in range(5):      
    scroller1=i*Y
    scroller2=(i+1)*Y
    Order="window.scrollTo("+str(scroller1)+", "+str(scroller2)+")"
    driver.execute_script(Order) 
    time.sleep(0.2)
        
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'lxml')

结果正确显示所有 25 个条目!

【讨论】:

    【解决方案2】:

    为您的请求使用手机用户代理,它会起作用

    page=requests.get('https://www.willhaben.at/iad/gebrauchtwagen/auto/ford-gebrauchtwagen/mustang' , headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1'} )
    

    还可以尝试将流属性设置为 true 并使用此代码

    for line in r.iter_lines():
    
        if line:
            print(json.loads(line))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多