如何找到正确的 python urllib2 splitted_page 列表索引?
How do I find the correct python urllib2 splitted_page list index?
我无法获取此 splitted_page 中的内容。我只想要标题 "Sian Blake partner ..."
这是我的代码。它打印的信息似乎比我需要的多
import urllib2
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
request = urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<h1 class=\"story-body\">");
splitted_page = splitted_page[0].split("</h1>")
print splitted_page[0]
谢谢。
可能你有问题,因为你使用了错误的 class - 它必须是 story-body__h1
我更喜欢 requests
和 lxml
所以我用它们来创建工作示例
import requests
import lxml, lxml.html
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
r = requests.get(url)
html = lxml.html.fromstring(r.content)
print(html.cssselect('.story-body__h1')[0].text)
编辑: 现在您的代码也可以工作了 - 您需要 story-body__h1
和 [1]
代替 [0]
import urllib2
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
request = urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<h1 class=\"story-body__h1\">");
splitted_page = splitted_page[1].split("</h1>") # [1] instead of [0]
print splitted_page[0]
我无法获取此 splitted_page 中的内容。我只想要标题 "Sian Blake partner ..."
这是我的代码。它打印的信息似乎比我需要的多
import urllib2
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
request = urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<h1 class=\"story-body\">");
splitted_page = splitted_page[0].split("</h1>")
print splitted_page[0]
谢谢。
可能你有问题,因为你使用了错误的 class - 它必须是 story-body__h1
我更喜欢 requests
和 lxml
所以我用它们来创建工作示例
import requests
import lxml, lxml.html
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
r = requests.get(url)
html = lxml.html.fromstring(r.content)
print(html.cssselect('.story-body__h1')[0].text)
编辑: 现在您的代码也可以工作了 - 您需要 story-body__h1
和 [1]
代替 [0]
import urllib2
url="http://www.bbc.co.uk/news/uk-england-london-35412127"
request = urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<h1 class=\"story-body__h1\">");
splitted_page = splitted_page[1].split("</h1>") # [1] instead of [0]
print splitted_page[0]