【问题标题】:Using Python 3.4 and Beautiful Soup to handle Ajax Pagination使用 Python 3.4 和 Beautiful Soup 处理 Ajax 分页
【发布时间】:2015-09-08 08:47:25
【问题描述】:

这是我第一次尝试python并在这里提出问题,所以我提前为这个问题的任何不正确结构道歉。

以下代码运行良好。

我遇到的问题是下面的脚本会刮掉第一页,但是我无法解决如何让代码触发下一个按钮,以便我可以遍历该数据等等。

在浏览器中,当您单击“下一步”按钮时,url 保持不变,但表中的数据已刷新并显示出相应的结果。

所以我假设该站点正在使用 ajax 来重新填充表格。

因此我的问题是如何以编程方式让 python 设置 ajax 以用下一批数据重新填充表?

import requests
from bs4 import BeautifulSoup
from datetime import datetime


# this crawls the url below for Primary and Secondary Schools throughout Australia
# and returns the Index(as a href link) for the details from the Href Link in the Index Output

# get the current date Time for the file labels
f_date = format(datetime.now().strftime('%Y%m%d'))
# set the Index File Name
index_file_title = ('education_primary_secondary_index_' + f_date + '.csv')
index_error_file_title = ('education_primary_secondary_index_errors_' + f_date + '.csv')
f_index = open(index_file_title, 'w')
f_index_errors = open(index_error_file_title, 'w')


def education_primary_secondary_index_spider(max_pages):
    page = 1
    url = "http://www.australianschoolsdirectory.com.au/search-result.php"
    striped_url = "http://www.australianschoolsdirectory.com.au"
    while page <= max_pages:
        source_code = requests.get(url)
        #plain_text = source_code.text
        soup = BeautifulSoup(source_code.text, "html.parser")
        for school_index_links in soup.find_all('a', {'class': 'clearfix'}):
            try:
                school_index_href = striped_url + school_index_links.get('href')
                f_index.write(str(school_index_href) + '\n')
            except Exception as e:
                f_index_errors.write(str(page) + '-----' + str(e) + '\n')
                pass
                # call to Details Module
                #education_primary_secondary_details_spider(index_href)
        page += 1

education_primary_secondary_index_spider(1)

【问题讨论】:

    标签: ajax python-3.x beautifulsoup


    【解决方案1】:

    下一步按钮将 POST 请求投射到 http://www.australianschoolsdirectory.com.au/search-result.php,表单数据具有“pageNum: 2”。您可以通过打开浏览器的开发控制台来检查这一点(chrome 和 firefox 中的 F12),转到网络选项卡并开始录制,然后单击下一步。

    由于我懒得找出请求中究竟需要什么才能对服务器有效,我通常将整个请求复制为 curl,并将其转换为请求请求:http://curl.trillworks.com/ 因此,这将为您提供 x 页的文本:

    import requests
    
    headers = {
        'Pragma': 'no-cache',
        'Origin': 'http://www.australianschoolsdirectory.com.au',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,cs;q=0.6',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Cache-Control': 'no-cache',
        'Referer': 'http://www.australianschoolsdirectory.com.au/search-result.php',
        'Connection': 'keep-alive',
    }
    x = 2
    data = 'searchType=&Boarding=&Special=&Alternative=&Religion=&noRefine=&schoolName=&distanceCalc=&searchWithin=&list_state=&list_state2=&school_id=&search=true&pageNum=' + x + '&searchType=&specialNeeds=&alternative=&religion=&type=&level=&gender=&flashfile=&feature=&list_region=&list_subreg=&list_subreg2='
    
    r = requests.post('http://www.australianschoolsdirectory.com.au/search-result.php', headers=headers, data=data)
    

    【讨论】:

    • 感谢您的回复。我已经想通了,我加载了 selenium 并在大约 3 行代码内完成了工作。
    • 是的 selenium 是另一种选择,可能更慢,但更容易编码:)
    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多