我用python抓取了一系列的超链接,我想从这些超链接中提取特定的字符串。 超链接如下: “http://tianqi.2345.com/hongkong/61063.htm”
它包含一个城市名称(香港)和一个城市ID(61063),我想得到以下结果:
cityName=hongkong
cityID = 61063
我的示例代码如下:
import re
reNamedGroupTestStr = 'http://tianqi.2345.com/qinxian/61063.htm'
foundTagA = re.search('http://tianqi.2345.com/(?P<CityName>.+?)/(?P<CityID>.+?).htm", reNamedGroupTestStr);
if(foundTagA):
GroupCityName = foundTagA.group("CityName");
print "CityName=",GroupCityName; #I wish to print 'hongkong'
GroupCityID = foundTagA.group("CityID");
print "CityID=",GroupCityID; #I wish to print '61063'
但是代码抛出bug,我不熟悉regex,有人能帮我吗?你知道吗
以下是我的完整代码:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(open("countyID.html"), "lxml")
#print(soup.prettify())
i = 0
for tag in soup.select('div.bmeta'):
if i == 5:
countys = tag
i = i + 1
for county in countys.find_all('a'):
countyid = county.get('href')
print county.get_text() #Print the city Chinese Name
print countyid[23:-10] #print the cityName
print countyid[-9:-4] #print the cityID
print '***'
#break
'''
the sample print result:
***
台北 #Print the city Chinese Name
taipei #print the cityName
71294 #print the cityID
***
'''
#test regex(corrected)
reNamedGroup = 'http://tianqi.2345.com/qinxian/61063.htm'
foundTagA = re.search('http://tianqi.2345.com/(?P<CityName>\w+?)/(?P<CityID>\d+?).htm', reNamedGroup)
if(foundTagA):
GroupCityName = foundTagA.group("CityName");
print "CityName=",GroupCityName; #I wish to print 'hongkong'
GroupCityID = foundTagA.group("CityID");
print "CityID=",GroupCityID; #I wish to print '61063'
您可以拆分:
这将给你:
如果要检查url是否与主机一起启动:
由于您使用的是BeautifulSoup,因此可以使用包含链接的div的id自己过滤锚定标记:
输出如下:
我不能添加所有的输出,因为我得到了一个关于垃圾邮件的警告,但它都在那里。你知道吗
另一种替代方法是使用
urlparse
(Python2 Doc/Python3 Doc)上面的代码应该有用。你知道吗
我没有使用
.
作为通配符搜索,而是使用特定的\w
和\d
来提高效率相关问题 更多 >
编程相关推荐