【问题标题】:how do you get links with certain words using beautifulsoup你如何使用beautifulsoup获得某些单词的链接
【发布时间】:2015-03-11 20:12:57
【问题描述】:

此代码用于从 html 网页获取链接,但我想让它只给我带有某些单词的链接。 例如,只有在 URL 中有这个词的链接:"www.mywebsite.com/word"

我的代码:

import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.mywebsite.com')



for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):

    if link.has_key('href'):
        print link['href']`

【问题讨论】:

    标签: python url web beautifulsoup httplib2


    【解决方案1】:

    您可以使用 in 进行简单的字符串搜索。下面的示例仅打印在 href 中包含“/website-builder”的链接。

    if '/website-builder' in link['href']:
        print link['href']
    

    完整代码:

    import httplib2
    from BeautifulSoup import BeautifulSoup, SoupStrainer
    
    http = httplib2.Http()
    status, response = http.request('http://www.mywebsite.com')
    
    for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
        if link.has_key('href'):
            if '/website-builder' in link['href']:
              print link['href']
    

    样本输出:

    /website-builder?linkOrigin=website-builder&linkId=hd.mainnav.mywebsite
    /website-builder?linkOrigin=website-builder&linkId=hd.subnav.mywebsite.mywebsite
    /website-builder?linkOrigin=website-builder&linkId=hd.subnav.hosting.mywebsite
    /website-builder?linkOrigin=website-builder&linkId=ct.btn.stickynavigation.easy-to-use#easy-to-use
    

    【讨论】:

    • 你能解释一下什么是汽车吗?以及你想在 auto 中计算什么?
    • 另外请接受答案,我认为它是正确的。
    • 只需在 for 循环之前将变量计数设置为零,并为找到的每个匹配项加一。
    • 没问题:)。如果要感谢您,请接受答案 :) 如果您不知道该怎么做,那么这里是链接说明:stackoverflow.com/help/someone-answers
    • count = 0 for BeautifulSoup 中的链接(response, parseOnlyThese=SoupStrainer('a')): count = count + 1 print 'Count: ', count i make it before for loop and it doesn't give我有什么有用的歌声
    【解决方案2】:

    这是我想出的:

    links = [link for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')) if link.find("word") != -1]
    print links
    

    当然,您应该将“word”替换为您希望过滤的任何单词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多