Python beautifulsoup 用于 Web 提取在标签的实际页面加载之前加载数据

Python beautifulsoup for web extraction loads data before the actual page of tags loads

我正在使用此代码从 link https://website.grader.com/results/www.dubizzle.com

中删除一些数据

代码如下

#!/usr/bin/python
import urllib
from bs4 import BeautifulSoup
from dateutil.parser import parse
from datetime import timedelta

import MySQLdb
import re
import pdb
import sys
import string

def getting_urls_of_all_pages(): 
    url_rent_flat='https://website.grader.com/results/dubizzle.com'
    every_property_in_a_page_data_extraction(url_rent_flat) 


def every_property_in_a_page_data_extraction(url):

    htmlfile=urllib.urlopen(url).read()
    soup=BeautifulSoup(htmlfile)

    print soup

    Sizeofweb=""
    try:

        Sizeofweb= soup.find('span', {'data-reactid': ".0.0.3.0.0.3.[=12=].1.1.0"}).text
        print Sizeofweb.get_text().encode("utf-8")

    except StandardError as e:
        error="Error was {0}".format(e)
        print error

getting_urls_of_all_pages()

我提取的html部分如下

快照: https://www.dropbox.com/s/7dwbaiyizwa36m6/5.PNG?dl=0

代码:

<div class="result-value" data-reactid=".0.0.3.0.0.3.[=13=].1.1">
<span data-reactid=".0.0.3.0.0.3.[=13=].1.1.0">1.1</span>
<span class="result-value-unit" data-reactid=".0.0.3.0.0.3.[=13=].1.1.1">MB</span>
</div>

问题: 问题是该网站需要大约 10-15 秒来加载 html 源文件,该文件包含我想要提取的标签,如代码中所述。

当代码使用 htmlfile=urllib.urlopen(url).read() 行加载页面的 html 时,我认为它加载了之前 link 的预加载 html 10-15 秒。

我如何暂停代码并让它在 15 秒以上后加载数据,以便 html 带有我想在程序中提取加载的标签?

使用 Selenium WebDriver 将解决您的问题。具体来说,它有一种方法可以等待指定的秒数以进行进一步处理。像下面这样的东西应该可以工作。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
driver.get(baseurl)

try:
    wait = WebDriverWait(driver, 60) 
    element = wait.until(
      ec.element_to_be_clickable(...)
    )
finally:
    driver.quit()