【问题标题】:Looping through web pages to webscrape data循环浏览网页以抓取网页数据
【发布时间】:2017-06-08 17:14:14
【问题描述】:

我正在尝试遍历 Zillow 页面并提取数据。我知道每次迭代后都会使用新的页码更新 URL,但提取的数据就像 URL 仍在第 1 页上一样。

import selenium
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import pandas as pd

next_page='https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/'

num_data1=pd.DataFrame(columns=['name','number'])

browser=webdriver.Chrome()
browser.get('https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/')

while True:

    page=requests.get(next_page)

    contents=page.content

    soup = BeautifulSoup(contents, 'html.parser')

    number_p=soup.find_all('p', attrs={'class':'ldb-phone-number'},text=True)
    name_p=soup.find_all('p', attrs={'class':'ldb-contact-name'},text=True)

    number_p=pd.DataFrame(number_p,columns=['number'])
    name_p=pd.DataFrame(name_p,columns=['name'])

    num_data=number_p['number'].apply(lambda x: x.text.strip())
    nam_data=name_p['name'].apply(lambda x: x.text.strip())

    number_df=pd.DataFrame(num_data,columns=['number'])
    name_df=pd.DataFrame(nam_data,columns=['name'])

    num_data0=pd.concat([number_df,name_df],axis=1)

    num_data1=num_data1.append(num_data0)

        try:

            button=browser.find_element_by_css_selector('.zsg-pagination>li.zsg-pagination-next>a').click()
            next_page=str(browser.current_url)

        except IndexError:

            break

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    page=requests.get(next_page) 替换为page = browser.page_source

    基本上发生的事情是,您将转到 Chrome 中的下一页,但随后尝试使用请求加载该页面的 url,这些请求被 Zillow 重定向回第一页(可能是因为它没有 cookie 或适当的请求标头)。

    【讨论】:

      【解决方案2】:

      为什么不让您的生活更轻松并使用Zillow API 而不是抓取? (您甚至有权抓取他们的网站吗?)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多