我需要使用Selenium或LXML抓下下一页2,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的解决方案(快速谷歌搜索显示其中一堆,以及关于此问题的StackOverflow答案),或者您可以坚持使用Selenium抓取代码并自己实施排队机制, Scrapy。