Python HTML - 按属性获取元素

时间:2012-02-26 03:08:14

标签: python html

我经常阅读有一个音乐网站,它有一个部分,用户发布他们自己虚构的音乐相关故事。有一个91部分系列(写一段时间,按部分上传)始终遵循以下惯例: http://www.ultimate-guitar.com/columns/fiction/riot_band_blues_part_#.html

我希望能够从每个部分获取格式化的文本并将其放入一个html文件中。

方便地,有一个指向打印版本的链接,为我的目的正确格式化。我所要做的就是编写一个脚本来下载所有部件,然后将它们转储到文件中。不难。

不幸的是,打印版本的网址如下: www.ultimate-guitar.com/print.php?what=article&id=95932

了解哪篇文章与哪个ID字段对应的唯一方法是查看原始文章中某个输入标记的value属性。

我想做的是:

Go to each page, incrementng through the varying numbers.

Find the <input> tag with attribute 'name="rowid"' and get the number in it's 'value=' attribute.

Go to www.ultimate-guitar.com/print.php?what=article&id=<value>.
Append everything (minus <html><head> and <body> to a html file.

Rinse and repeat.

这可能吗? python是正确的语言吗?另外,我应该使用什么dom / html / xml库?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用lxml和urllib2:

import lxml.html
import urllib2

#implement the logic to download each page, with HTML strings in a sequence named pages
url = "http://www.ultimate-guitar.com/print.php?what=article&id=%s"

for page in pages:
    html = lxml.html.fromstring(page)
    ID = html.find(".//input[@name='rowid']").value
    article = urllib2.urlopen(url % ID).read()
    article_html = lxml.html.fromstring(article)
    with open(ID + ".html", "w") as html_file:
        html_file.write(article_html.find(".//body").text_content())

编辑:运行此命令后,页面中可能会出现一些Unicode字符。解决这个问题的一种方法是执行article = article.encode("ascii", "ignore")或将编码方法放在.read()之后,强制使用ASCII并忽略Unicode,尽管这是一个懒惰的修复。

这假设您只需要body标签内所有内容的文本内容。这将在Python文件的本地目录中以storyID.html(所以“95932.html”)的格式保存文件。如果您愿意,可以更改保存语义。

答案 1 :(得分:0)

你可以在javascript / jquery中实现这一点而不会有太多麻烦。 javascripty-pseudocode,附加到空文档:

for(var pageNum = 1; i<= 91; i++) {
    $.ajax({
        url: url + pageNum,
        async: false,
        success: function() {
            var printId = $('input[name="rowid"]').val();
            $.ajax({
                url: printUrl + printId,
                async: false,
                success: function(data) {
                    $('body').append($(data).find('body').contents());
                }
            });
        }
    });
}

加载完成后,您可以将生成的HTML保存到文件中。

相关问题