分析并提取html页面中的链接
我刚接触Python,遇到了一些简单的问题。
我有一个HTML页面,想分析一下,提取特定表格里的链接。
在bash里,我可以用lynx --source,然后用grep/cut来处理,这样没问题……但在Python里我不知道该怎么做。
我想尝试这样做:
import urllib2
data = urllib2.urlopen("http://www.my_url.com")
这样做的话,我得到了整个HTML页面。
然后我想试试:
for line in data.read():
if "my_links" in line:
print line
但是好像不太管用。
3 个回答
0
你为什么不直接使用 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
0
一般来说,你需要用到Xpath来实现这些目的。
举个例子:http://www.w3schools.com/xpath/xpath_examples.asp
Python有一个很棒的库叫做 lxml
:
http://lxml.de/xpathxslt.html
1
关于你的代码问题,这段代码会一个字符一个字符地读取数据。如果你不告诉它要读取多少数据的话。
for line in data.read():
你可以这样做:
line = data.readline()
while(line):
print line
line = data.readline()
这部分并不是一个直接的答案,但我建议你使用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