从html页面分析并获取链接

2024-05-17 06:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,在做一件简单的事情时遇到了一些问题。在

我有一个html页面,我想分析它并在一个specific表中获取一些链接。在

在bash中我会使用lynx-source,使用grep/cut我没有问题……但是在Python中我不知道怎么做。。在

我想做些类似的事情:

import urllib2

data = urllib2.urlopen("http://www.my_url.com")

这样我就得到了整个html页面。在

然后我想:

^{pr2}$

但似乎没用


Tags: importbashsourcedata链接html页面urllib2
3条回答

为什么不简单地使用enumerate()

site=urllib2.urlopen(r'http://www.rom.on.ca/en/join-us/jobs')

for i,j in enumerate(site):
     if "http://www.ontario.ca" in j: #j is the line
         print i+1 #i is the number start from 0 normally in the html code is 1 the first line so add +1

>>620 

在您的代码问题上,这将逐字读取。如果不传递要读取的数据量。在

for line in data.read():

你可以:

^{pr2}$

这部分不完全是一个答案,但我建议您使用BeautifulSoup。在

import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.my_url.com"
data = urllib2.urlopen(url).read()
soup = BeautifulSoup.BeautifulSoup(data)

all_links = soup.find('a')
# you can look for specific link

一般情况下,您需要Xpath来实现这些目的。 示例:http://www.w3schools.com/xpath/xpath_examples.asp

Python有一个漂亮的库lxmlhttp://lxml.de/xpathxslt.html

相关问题 更多 >