使用Python使用AJAX分页的站点使用BeautifulSoup进行刮擦

Jol*_*aha 2 python ajax selenium pagination beautifulsoup

我是编码和Python的新手,所以如果这是一个愚蠢的问题我会道歉.我想要一个遍历所有19,000个搜索结果页面的脚本,并为每个网址抓取所有网址.我已经完成了所有的报废工作,但无法弄清楚如何处理页面使用AJAX进行分页的事实.通常我只是使用url创建一个循环来捕获每个搜索结果,但这是不可能的.这是页面:http://www.heritage.org/research/all-research.aspx?cars&category = report

这是我到目前为止的脚本:

with io.open('heritageURLs.txt', 'a', encoding='utf8') as logfile:
    page = urllib2.urlopen("http://www.heritage.org/research/all-research.aspx?nomobile&categories=report")
    soup = BeautifulSoup(page)
    snippet = soup.find_all('a', attrs={'item-title'})
    for a in snippet:
        logfile.write ("http://www.heritage.org" + a.get('href') + "\n")

print "Done collecting urls"
Run Code Online (Sandbox Code Playgroud)

显然,它会刮掉结果的第一页,仅此而已.

我已经看了几个相关的问题,但似乎没有人使用Python,或者至少不是以我能理解的方式.预先感谢您的帮助.

Anz*_*zel 5

为了完整起见,您可以尝试访问POST请求并找到一种方法来访问下一页,就像我在评论中建议的那样,如果可以替代,使用Selenium将很容易实现您想要的.

这是一个使用Selenium的简单解决方案:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

# uncomment if using Firefox web browser
driver = webdriver.Firefox()

# uncomment if using Phantomjs
#driver = webdriver.PhantomJS()

url = 'http://www.heritage.org/research/all-research.aspx?nomobile&categories=report'
driver.get(url)

# set initial page count
pages = 1
with open('heritageURLs.txt', 'w') as f:
    while True:
        try:
            # sleep here to allow time for page load
            sleep(5)
            # grab the Next button if it exists
            btn_next = driver.find_element_by_class_name('next')
            # find all item-title a href and write to file
            links = driver.find_elements_by_class_name('item-title')
            print "Page: {} -- {} urls to write...".format(pages, len(links))
            for link in links:
                f.write(link.get_attribute('href')+'\n')
            # Exit if no more Next button is found, ie. last page
            if btn_next is None:
                print "crawling completed."
                exit(-1)
            # otherwise click the Next button and repeat crawling the urls
            pages += 1
            btn_next.send_keys(Keys.RETURN)
        # you should specify the exception here
        except:
            print "Error found, crawling stopped"
            exit(-1)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.