Python web递归浏览(下一页)

2024-05-20 10:10:42 发布

您现在位置:Python中文网/ 问答频道 /正文

3条回答

你可以试试这个:

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

我希望这有帮助。。。你知道吗

对于这类问题,通常的解决方案不是使用循环来遍历“所有页面”(因为您不知道前面有多少页面),而是使用某种队列,在这种队列中,刮取一个页面会选择性地将后续页面添加到队列中,稍后再刮取。你知道吗

在您的特定示例中,在抓取每个页面的过程中,您可以查找指向“下一页”的链接,如果该链接在那里,则将下一页的URL添加到队列中,这样它将在当前页面之后被抓取;一旦您找到没有“下一页”链接的页面,队列将清空,抓取将停止。 一个更复杂的示例可能包括刮除一个类别页面,并将其每个子类别作为后续页面添加到刮除队列中,每个子类别又可能将多个项目页面添加到队列中,等等

看看像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的解决方案(快速google显示了其中的一组,以及关于这个问题的StackOverflow答案),或者您可以坚持使用Selenium scraping代码,自己实现一个队列机制,而不使用Scrapy。你知道吗

相关问题 更多 >