python正则表达式:在hyperlin中提取特殊子字符串

2024-06-26 17:49:10 发布

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

我用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'

Tags: thetorecomhttpgroupprintwish
3条回答

您可以拆分:

u = "http://tianqi.2345.com/hongkong/61063.htm"


_, nme, c_id = u.rsplit("/", 2)
print(nme, c_id.split(".", 1)[0])

这将给你:

hongkong 61063

如果要检查url是否与主机一起启动:

if u.startswith("http://tianqi.2345.com/"):
     _, nme, c_id = u.rstrip(".htm").rsplit("/", 2)

由于您使用的是BeautifulSoup,因此可以使用包含链接的div的id自己过滤锚定标记:

from bs4 import BeautifulSoup

import requests

soup = BeautifulSoup(requests.get("http://tianqi.2345.com/").content)

for a in soup.select("#hot_l a[href]"):
    print(a.text)
    _, nme, c_id = a["href"].rsplit("/", 2)
    print(nme, c_id.split(".", 1)[0])

输出如下:

北京
beijing 54511

我不能添加所有的输出,因为我得到了一个关于垃圾邮件的警告,但它都在那里。你知道吗

另一种替代方法是使用urlparsePython2 Doc/Python3 Doc

# For Python 2
>>> from urlparse import urlparse

# For Python 3
>>> from urllib.parse import urlparse

>>> o = urlparse("http://tianqi.2345.com/hongkong/61063.htm")
>>> l = o.path.split("/")
>>> l[1]
'hongkong'
>>> l[2].split(".")[0]
'61063'
foundTagA = re.search('http://tianqi.2345.com/(?P<CityName>\w+?)/(?P<CityID>\d+?).htm', reNamedGroupTestStr)

上面的代码应该有用。你知道吗

我没有使用.作为通配符搜索,而是使用特定的\w\d来提高效率

相关问题 更多 >