【问题标题】:I am trying to scrape website, but I encountered a problem. When I try to scrape data, it looks like the html differs from what I see on我正在尝试抓取网站,但遇到了问题。当我尝试抓取数据时,看起来 html 与我看到的不同
【发布时间】:2021-02-18 05:01:33
【问题描述】:

我正在尝试抓取网站,但遇到了问题。当我尝试抓取数据时,看起来 html 与单击检查选项时看到的不同。我正在尝试抓取“https://bri.co.id/en/lokasi”网站以获取银行所有分行的分行名称和地址。

from bs4 import BeautifulSoup

from selenium import webdriver

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.by import By

from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome("C:/Users/manisha.rawat/Downloads/chromedriver.exe")

URL = 'https://bri.co.id/en/lokasi'

driver.get(URL)

soup = BeautifulSoup(driver.page_source, 'html.parser')

driver.quit()

print(soup.find('div',class_="address"))

代码只打印一个地址。我需要所有的地址。谁能建议我做错了什么?

【问题讨论】:

    标签: python selenium-webdriver web-scraping beautifulsoup


    【解决方案1】:

    尝试以下使用 python 的方法 - requests 简单、直接、可靠、快速且在处理请求时需要更少的代码。在检查了谷歌浏览器的网络部分后,我从网站本身获取了 API URL。

    下面的脚本到底在做什么:

    1. 首先它将获取创建的 API URL,查询字符串参数、标题、表单数据及其动态参数(全部大写)并执行 POST 请求。

    2. 表单数据是动态的,您可以在参数中传递任何有效值,并且每次您想从站点获取内容时都会为您创建数据。(重要的是不要更改 Page_No 参数的值)。

    3. 获取数据后脚本会使用json.loads库解析JSON数据。

    4. 最后,它将遍历每次迭代或页面中获取的地址列表,例如:地址、名称、代理代码、地图 URL、电话等,您可以根据需要修改这些属性。

      def scrape_addresses():
      
        url = "https://bri.co.id/en/lokasi" # API URL
      
        querystring = {"p_p_id":"location_display_ortlet","p_p_lifecycle":"2",
                 "p_p_state":"normal","p_p_mode":"view",
                 "p_p_resource_id":"/location/ui/search",
                 "p_p_cacheability":"cacheLevelPage"}  # API URL query string parameters !Important to add
        headers = {
             'content-type': "application/x-www-form-urlencoded",
             'cache-control': "no-cache"
                  }    # headers and type !Important to add
        #Parameters to create form data (Change as per your need except Page_No parameter)
        PAGE_NO = 1
        LOCATION_TYPE = ''
        PROVINCE = ''
        SERVICE = ''
      
        while True:
            print('Creating new form data for page no : ' + str(PAGE_NO))
            # Request payload or form-data !Important to add
            payload = '_location_display_ortlet_page=' + str(PAGE_NO) + 
                     '&_location_display_ortlet_locationType=' + LOCATION_TYPE + 
                     '&_location_display_ortlet_province=' + PROVINCE + 
                     '&_location_display_ortlet_service=' + SERVICE
      
            # POST request with provided URL
            response = requests.post(url, data=payload, headers=headers, 
                         params=querystring,verify = False)
      
            print('Created new form data going to fetch data...')
      
            result = json.loads(response.text) #Parse result using JSON loads
      
            if len(result) == 0:
               break
            else:
               extracted_data = result['data']
               for data in extracted_data:
                   print('-' * 100)
                   print('Fetching data for : ' , data['name'])
                   print('Address : ', data['address'])
                   print('Agent Code : ',data['agentCode'])
                   print('ID : ', data['id'])
                   print('Latitude : ',data['latitude'])
                   print('Longitude : ',data['longitude'])
                   print('Name : ',data['name'])
                   print('Opening Hours : ',data['openingHours'])
                   print('Phone : ', data['phone'])
                   print('Service Offered : ',data['serviceOffered'])
                   print('Type : ',data['type'])
                   print('Maps URL : ',data['urlMaps'])
                   print('-' * 100)
          PAGE_NO += 1 #increment page number after each iteration to scrap more data
       scrape_addresses()
      

    【讨论】:

    • 您好,您能解释一下如何获取API url查询字符串参数吗?我尝试了右键单击、检查和网络选项,但不知道如何继续?
    • 只需打开网络选项卡并单击 XHR 选项,它将过滤并显示所有 AJAX 调用。我建议在单击 XHR 命中刷新后检查每个 AJAX 调用 > API 调用的预览选项卡。在预览选项卡中只需搜索您正在寻找的数据,但不能保证您会在每个网站中获得数据。万事如意..
    【解决方案2】:

    find method 的文档非常清楚:它只给你第一个结果。

    要获取过滤器的所有结果,请使用find_all

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多