Python:在HTML<a>标记中查找特定链接

2024-09-26 18:13:16 发布

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

在Python中,我有一个包含网站源代码的字符串。在这个源代码中,如果标记包含一个特定的子字符串,我想获取标记中的链接。在

输入如下:

AnyKindOfString <a href="http://www.link-to-get.com">SearchString</a> AndEvenMoreString

所以我想告诉Python的是在字符串内的所有标记中搜索SearchString,并将第一个找到的http://www.link-to-get.com返回给我。在

只有当SearchString在标记内时,这才有效,而且如果“SearchString”是http://www.link-to-get.com的一部分(子字符串),它也应该起作用。在

我在寻找一个答案,比如30多分钟就知道了,我发现Python的唯一方法就是从一个字符串中提取每个(或仅外部或内部)链接。在

有人有主意吗?在

提前通知!在


Tags: to字符串标记comhttpget源代码网站
3条回答

我已经粗略地列出了一些应该可以工作的代码,至少在你给出的示例字符串上是有效的。在

myString = 'AnyKindOfString <a href="http://www.link-to-get.com">SearchString</a> AndEvenMoreString'

theLimit = len(myString)
searchStringLinkPairs = []
tempStr = myString[:]
i =0


while i < theLimit:
    startLoc = tempStr.find('<a')
    endLoc = tempStr.find("</a")
    print startLoc,"\t",endLoc
    subStr = tempStr[startLoc:endLoc]
    startLink = subStr.find("\"")
    subTwo = subStr[startLink+1:]
    endLink = subTwo.find("\"")
    myLink = subStr[startLink+1:startLink+1+endLink]

    searchStringStart = subStr.find(">")
    searchString = subStr[searchStringStart+1:endLoc]

    if myLink != "" and searchString != "":
        searchStringLinkPairs.append([myLink, searchString])
    tempStr = tempStr[endLoc+1:]
    i = endLoc
    if startLoc == -1 or endLoc == -1:
        i = 10 * theLimit

print searchStringLinkPairs

在python2.7中使用beauthoulsoup3.2.1

from BeautifulSoup import BeautifulSoup

search_string = 'SearchString'

website_source = '<a href="http://www.link-to-get.com">SearchString</a> <a href="http://www.link-to-get.com">OtherString</a>\
                  <a href="http://www.link-to-getSearchString.com">otherString</a>'

soup = BeautifulSoup(website_source)

# this will return a list of lists that has the url's and the name for the link
anchors = [[row['href'], row.text] for row in soup.findAll('a') if row['href'].find(search_string) <> -1 or search_string in row.text]

# prints whole list
print anchors

#prints first list
print anchors[0]

# prints the url for the first list
print anchors[0][0]

问题似乎是我用beauthoulsoup3.2.1测试了上述内容,它只在python2.x中运行,而您使用的是python3.4,因此出现了错误。
如果你安装BeautifulSoup4并尝试下面的代码,它应该可以工作。还要注意的是,beauthoulsoup4可以在2.x和3.x中工作

请注意,以下内容尚未测试。在

^{pr2}$

可以在pyqueryhttp://pythonhosted.org/pyquery/index.html)+lxmlhttp://lxml.de/tutorial.html)的帮助下完成,如下所示

from pyquery import PyQuery as pq
from lxml import etree

pq_obj = pq(etree.fromstring('<body><p>AnyKindOfString <a href="http://www.link-to-get.com">SearchString</a> AndEvenMoreString</p><p>this is another string goes here</p><a> other</a></body>'))
search_string = 'SearchString'

links = pq_obj('a')
for link in links:
    if search_string in link.text:
        attrib = link.attrib
        print attrib.get('href')

# output
# http://www.link-to-get.com

相关问题 更多 >

    热门问题