python lxml没有显示所有内容

时间:2015-11-28 17:41:38

标签: python html parsing web-scraping lxml

我正在尝试抓取网页的特定部分,并最终计算单词频率。但我发现很难得到整篇文章。据我所知,从HTML代码中可以看出,我的脚本省略了该部分中的断行但没有<br>标记的部分。 我的代码:

import urllib
from lxml import html as LH
import lxml
import requests

scripturl="http://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=the-sopranos&episode=s06e21"
scripthtml=urllib.urlopen(scripturl).read()

scripthtml=requests.get(scripturl)
tree = LH.fromstring(scripthtml.content)
script=tree.xpath('//div[@class="scrolling-script-container"]/text()')
print script
print type(script)

这是输出:

  

[&#34; \ n \ n \ n \ n \ t \ t \ t(电台点击,\ r \ n播放音乐)\ r \ n \ r \ n唱片骑师:\ r \
  纽约的经典摇滚\ r \ nq104。&#34;,&#39; 3。&#39;,&#39;
  \ r \ n \ r \ n早上好。&#39;,&#34; \ r \ n我是吉姆克尔。&#34;,   &#39; \ r \ n \ r \ n来了\ r \ n

当我迭代结果时,只有/ r后面的短语,后跟逗号或双逗号。

for res in script:
    print res

输出结果为:

  

Q104。   3。              早上好。              我是吉姆克尔。

我不仅限于lxml,但因为我比较新,所以我不熟悉其他方法。

2 个答案:

答案 0 :(得分:0)

lxml元素同时具有text和tail方法。您正在搜索文本,但如果元素中嵌入了HTML元素(例如br),则对文本的搜索将仅与解析器从元素的text()方法获取的第一个文本一样深。

尝试:

script = tree.xpath('//div[@class="scrolling-script-container"]')
print join(" ", (script[0].text(), script[0].tail()))

答案 1 :(得分:0)

这让我困扰,我写了一个解决方案:

import requests
import lxml
from lxml import etree
from io import StringIO

parser = etree.HTMLParser()
base_url = "http://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=the-sopranos&episode=s06e21"
resp = requests.get(base_url)
root = etree.parse(StringIO(resp.text), parser)

script = root.xpath('//div[@class="scrolling-script-container"]')
text_list = []

for elem in script:
    print(elem.attrib)
    if hasattr(elem, 'text'):
        text_list.append(elem.text)
    if hasattr(elem, 'tail'):
        text_list.append(elem.tail)

for elem in text_list:
# only gets the first block of text before 
# it encounters a br tag
        print(elem)

for elem in script:
# prints everything 
    for sib in elem.iter():
        print(sib.attrib)
        if hasattr(sib, 'text'):
            print(sib.text)
        if hasattr(sib, 'tail'):
            print(sib.tail)