【问题标题】:How to get an HTML file using Python?如何使用 Python 获取 HTML 文件?
【发布时间】:2011-05-28 05:38:33
【问题描述】:

我对 Python 不是很熟悉。我正在尝试从以下页面中提取艺术家姓名(开始:)):http://www.infolanka.com/miyuru_gee/art/art.html

如何检索页面?我的两个主要担忧是;使用哪些功能以及如何过滤掉页面中无用的链接?

【问题讨论】:

    标签: python html webclient


    【解决方案1】:

    使用 urllib 和 lxml.html 的示例:

    import urllib
    from lxml import html
    
    url = "http://www.infolanka.com/miyuru_gee/art/art.html"
    page = html.fromstring(urllib.urlopen(url).read())
    
    for link in page.xpath("//a"):
        print "Name", link.text, "URL", link.get("href")
    
    output >>
        [('Aathma Liyanage', 'athma.html'),
         ('Abewardhana Balasuriya', 'abewardhana.html'),
         ('Aelian Thilakeratne', 'aelian_thi.html'),
         ('Ahamed Mohideen', 'ahamed.html'),
        ]
    

    【讨论】:

    • 在 python 3 中你应该导入 urllib.request 并使用 urllib.request.urlopen 函数。见docs.python.org/3.2/library/…
    • urllib 在这个时代已经过时,应该使用 requests 库或处理现代问题的东西。
    【解决方案2】:

    我认为“eyquem”方式也是我的选择,但我喜欢使用 httplib2 而不是 urlliburllib2 对于这项工作来说是太低级的库。

    import httplib2, re
    pat = re.compile('<DT><a href="[^"]+">(.+?)</a>') http = httplib2.Http() headers, body = http.request("http://www.infolanka.com/miyuru_gee/art/art.html")
    li = pat.findall(body) print li

    【讨论】:

      【解决方案3】:
      1. 使用urllib2获取页面。

      2. 使用BeautifulSoup解析HTML(页面),得到你想要的!

      【讨论】:

        【解决方案4】:

        检查一下我的朋友

        import urllib.request
        
        import re
        
        pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')
        
        url = 'http://www.infolanka.com/miyuru_gee/art/art.html'
        
        sock = urllib.request.urlopen(url).read().decode("utf-8")
        
        li = pat.findall(sock)
        
        print(li)
        

        【讨论】:

          【解决方案5】:

          或者直接往前走:

          import urllib
          
          import re
          pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')
          
          url = 'http://www.infolanka.com/miyuru_gee/art/art.html'
          sock = urllib.urlopen(url)
          li = pat.findall(sock.read())
          sock.close()
          
          print li
          

          【讨论】:

            【解决方案6】:

            尊重 robots.txt 并限制您的请求 :)

            (显然 urllib2 已经按照 helpful SO post 做了)。

            【讨论】:

            • 不这样做违法吗? ^.^
            • 不,除非我误解了那里的多重否定。 :)
            【解决方案7】:

            基本上有一个函数调用:

            render_template()

            您可以使用它轻松返回单个页面或页面列表,它会显示 所有文件都来自 your_workspace\templates

            例子:

            /root_dir /templates /index1.html, /index2.html /other_dir /

            routes.py

            @app.route('/') def root_dir(): return render_template('index1.html')

            @app.route(/<username>) def root_dir_with_params(username): retun render_template('index2.html', user=username)

            index1.html - 没有参数

            <html> <body> <h1>Hello guest!</h1> <button id="getData">Get Data!</button> </body> </html>

            index2.html - 带参数

            <html> <body> <!-- Built-it conditional functions in the framework templates in Flask --> {% if name %} <h1 style="color: red;">Hello {{ user }}!</h1> {% else %} <h1>Hello guest.</1> <button id="getData">Get Data!</button> </body> </html>

            【讨论】:

              【解决方案8】:

              适用于 Python 3.x 并使用 requestsbs4 的更简洁的答案。尽管在原始问题中有两个问题。一、如何获取html:

              import requests
              html = requests.get("http://www.infolanka.com/miyuru_gee/art/art.html").content
              

              二、如何获取艺人名单:

              import bs4
              soup = bs4.BeautifulSoup(html)
              artist_list = []
              for i in soup.find_all("a"):
                  if i.parent.name == "dt":
                      artist_list.append(i.contents[0])
              print(artist_list)
              

              输出:

              ['Aathma Liyanage',
               'Abewardhana Balasuriya',
               'Aelian Thilakeratne',
               'Ahamed Mohideen',
               'Ajantha Nakandala',
               'Ajith Ambalangoda',
               'Ajith Ariayaratne',
               'Ajith Muthukumarana',
               'Ajith Paranawithana',
              ...]
              

              【讨论】:

                猜你喜欢
                • 2020-07-12
                • 1970-01-01
                • 1970-01-01
                • 2023-03-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-02-21
                • 1970-01-01
                相关资源
                最近更新 更多