Python 递归网页抓取(下一页)

Python web scaping recursively (next page)

来自这个网站: https://search2.ucl.ac.uk/s/search.html?query=max&collection=website-meta&profile=_directory&tab=directory&f.Profile+Type%7Cg=Student&start_rank=1

我需要使用 Selenium 或 LXML 抓取下一页 2、3 ...。 我只能抓取第一页

在 url 中更改 start_rank。例如:

https://search2.ucl.ac.uk/s/search.html?query=max&collection=website-meta&profile=_directory&tab=directory&f.Profile+Type%7Cg=Student&start_rank=11

你可以试试这个:

nextNumberIsThere = True
i=1
while nextNumberIsThere:
    driver.execute_script("document.body.scrollHeight");
    profileDetails = driver.find_elements_by_xpath("//ul[@class='profile-details']/li")
    for element in profileDetails:
        print(element.text)
    next = driver.find_elements_by_xpath("//a[text()='"+str(i)+"']")
    i+=1
    if len(next) > 0:
        next[0].click()
    else:
        nextNumberIsThere = False

以上代码将迭代并获取数据,直到没有数字为止。

如果您想分别获取姓名、部门、​​电子邮件,请尝试以下代码:

nextNumberIsThere = True
i=1
while nextNumberIsThere:
    driver.execute_script("document.body.scrollHeight");
    profileDetails = driver.find_elements_by_xpath("//ul[@class='profile-details']")
    for element in profileDetails:
        name = element.find_element_by_xpath("./li[@class='fn']")
        department = element.find_elements_by_xpath("./li[@class='org']")
        email = element.find_element_by_xpath("./li[@class='email']")
        print(name.text)
        print(department.text)
        print(email.text)
        print("------------------------------")
        next = driver.find_elements_by_xpath("//a[text()='"+str(i)+"']")
    i+=1
    if len(next) > 0:
        next[0].click()
    else:
        nextNumberIsThere = False

希望对您有所帮助...

这种问题的通常解决方案不是使用遍历 "all the pages" 的循环(因为你不知道前面有多少),而是使用某种队列,其中抓取一页可以选择将后续页面添加到队列中,以便稍后抓取。

在您的具体示例中,在每个页面的抓取过程中,您可以查找 link 到 "next page",如果存在,则将下一页的 URL 添加到队列中, 因此它将在当前页面之后被抓取;一旦你点击了一个没有 "next page" link 的页面,队列就会清空,抓取就会停止。 一个更复杂的示例可能包括抓取类别页面并将其每个子类别作为后续页面添加到抓取队列中,每个子类别又可能将多个项目页面添加到队列中,等等。

看看像 Scrapy 这样的抓取框架,它们在设计中很容易包含这种功能。您可能会发现它的一些其他功能也很有用,例如它能够使用 XPath 或 CSS 选择器在页面上查找元素。

Scrapy 主页上的第一个示例准确地展示了您要实现的功能类型:

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['https://blog.scrapinghub.com']

    def parse(self, response):
        for title in response.css('.post-header>h2'):
            yield {'title': title.css('a ::text').get()}

        for next_page in response.css('a.next-posts-link'):
            yield response.follow(next_page, self.parse)

关于 Scrapy 的一个重要说明:它不使用 Selenium(至少不是开箱即用的),而是下载页面源代码并对其进行解析。这意味着它不会 运行 JavaScript,如果您抓取的网站是客户端生成的,这对您来说可能是个问题。在这种情况下,您可以研究结合 Scrapy 和 Selenium 的解决方案(快速谷歌搜索显示了其中的一堆,以及关于这个问题的 Whosebug 答案),或者您可以坚持使用 Selenium 抓取代码并自己实现一个排队机制,而无需垃圾。