从python中的网页读取特定行

时间:2015-07-06 14:17:56

标签: python html webpage

在我的代码中,我试图将第一行文本从网页转换为python中的变量。目前我正在使用urlopen获取我想要阅读的每个链接的整个页面。我如何只阅读网页上的第一行文字。

我的代码:

import urllib2
line_number = 10
id = (np.arange(1,5))
for n in id:
    link =  urllib2.urlopen("http://www.cv.edu/id={}".format(n))
    l = link.read()

我想从以下网页的html代码中提取“旧车”这个词:

<html>
    <head>
        <link rel="stylesheet">
        <style>
            .norm { font-family: arial; font-size: 8.5pt; color: #000000; text-decoration : none; }
            .norm:Visited { font-family: arial; font-size: 8.5pt; color: #000000; text-decoration : none; }
            .norm:Hover { font-family: arial; font-size: 8.5pt; color : #000000; text-decoration : underline; }
        </style>
    </head>
    <body>
<b>Old car</b><br>
<sup>13</sup>CO <font color="red">v = 0</font><br>
ID: 02910<br>
<p>
<p><b>CDS</b></p>

2 个答案:

答案 0 :(得分:0)

如果您打算在许多不同的网页上执行此操作,您可能会发现BeautifulSoup很有帮助。

http://www.crummy.com/software/BeautifulSoup/bs4/doc/

正如您在快速入门底部所看到的那样,您应该可以从页面中提取所有文本,然后选择您感兴趣的任何行。

请注意,这仅适用于HTML文本。一些网页广泛使用javascript,而request / BeautifulSoup将无法读取javascript提供的内容。

Using Requests and BeautifulSoup - Python returns tag with no text

另请参阅我过去遇到过的问题,用户avi澄清了这个问题:Want to pull a journal title from an RCSB Page using python & BeautifulSoup

答案 1 :(得分:0)

使用XPath。这正是我们所需要的。

  

XPath XML路径语言,是一种用于从XML文档中选择节点的查询语言。

lxml python library将帮助我们解决这个问题。这是其中之一。 Libxml2Element TreePyXML是其中一些选项。有很多很多图书馆可以做这类事情。

使用XPath

根据您现有的代码,以下内容将起作用:

import urllib2
from lxml import html
line_number = 10
id = (np.arange(1,5))
for n in id:
    link =  urllib2.urlopen("http://www.cv.edu/id={}".format(n))
    l = link.read()
    tree = html.fromstring(l)
    print tree.xpath("//b/text()")[0]

XPath查询//b/text()基本上是“从页面上的<b>元素获取文本。tree.xpath函数调用返回一个列表,我们使用{{选择第一个1}}。轻松。

关于请求

在使用代码阅读网页时,Requests library是最先进的。它可能会在以后为您节省一些麻烦。

完整的程序可能如下所示:

[0]

注意事项

网址对我不起作用,所以你可能需要修补一下。但这个概念很合理。

从网页上读取,您可以使用以下内容来测试XPath:

from lxml import html
import requests

for nn in range(1, 6):
    page = requests.get("http://www.cv.edu/id=%d" % nn)
    tree = html.fromstring(page.text)
    print tree.xpath("//b/text()")[0]
相关问题