【问题标题】:loop not going to next page循环不去下一页
【发布时间】:2014-10-05 20:23:42
【问题描述】:

我刚刚制作了一个 python 脚本,该脚本可以访问律师的个人资料以获取他们的详细信息。它适用于第一页,但循环不会转到第二页。该脚本仅从第一页抓取数据。我想刮掉所有页面。请帮助我,我是 python 新手。

代码如下:

import requests

from lxml import html

root_url = 'http://lawyerlist.com.au/'

def get_page_urls(): 
  for no in ('1','2'):  
    page = requests.get('http://lawyerlist.com.au/lawyers.aspx?city=Sydney&Page=' + no)   
    tree = html.fromstring(page.text)
    return (tree.xpath('//td/a/@href'))

for li in (get_page_urls()):
  pag=requests.get(root_url + li) 
  doc = html.fromstring(pag.text)
  for name in doc.xpath('//tr/td/h1/text()'):
    print(name)

【问题讨论】:

    标签: python html lxml


    【解决方案1】:

    get_page_urls函数只返回第一页的url,因为for循环中有return语句。使用 yield 语句将函数转换为生成器,然后像这样遍历每页 url:

    import requests
    
    from lxml import html
    
    root_url = 'http://lawyerlist.com.au/'
    
    def get_page_urls(): 
      for no in ('1','2'):  
        page = requests.get('http://lawyerlist.com.au/lawyers.aspx?city=Sydney&Page=' + no)   
        tree = html.fromstring(page.text)
        yield tree.xpath('//td/a/@href')
    
    for page_of_urls in get_page_urls():
      for li in page_of_urls:
        pag=requests.get(root_url + li) 
        doc = html.fromstring(pag.text)
        for name in doc.xpath('//tr/td/h1/text()'):
          print(name)
    

    【讨论】:

    • 今天我学到了一些关于 python 的新知识。再次感谢您。先生,请您向我推荐任何适合我这样的初学者的在线 python 教程电子书。
    • @user3891081 看看Zed Shaw 的learn python the hardway,html 版本可以在线免费阅读link
    【解决方案2】:

    问题是for no in ('1', '2'):中的返回

    一旦达到此返回,它将停止运行循环并退出函数。您可以将 tree.xpath('//td/a/@href') 附加到列表中,然后在 for 循环之外返回列表。

    类似:

    def get_page_urls():
      all_trees = []
      for no in ('1','2'):  
        page = requests.get('http://lawyerlist.com.au/lawyers.aspx?city=Sydney&Page=' + no)   
        tree = html.fromstring(page.text)
        all_trees.append(tree.xpath('//td/a/@href'))
      return all_trees
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2020-12-22
      • 1970-01-01
      • 2012-05-02
      • 2014-12-23
      • 1970-01-01
      • 2015-12-18
      相关资源
      最近更新 更多