【问题标题】:Getting urls out of block of text?从文本块中获取网址?
【发布时间】:2013-11-25 02:19:52
【问题描述】:

我有一大段文本,想解析出所有的 URL,返回一个遵循这种模式的 url 列表:https://www.facebook.com/.*$.

这是我想从中解析的文本示例:

<abbr title="Monday xxxx" data-utime="xx" class="timestamp">over a year ago</abbr></div></div></div></div></div></li><li class="fbProfileBrowserListItem"><div class="clearfix _5qo4"><a class="_8o _8t lfloat" href="https://www.facebook.com/xxxxx?fref=pb&amp;hc_location=profile_browser" tabindex="-1" aria-hidden="true" data-hovercard="/ajax/hovercard/user.php?id=xxxx&amp;extragetparams=%7B%22hc_location%22%3A%22profile_browser%22%7D"><img class="_s0 _rw img" src="https://fbcdn-profile-xxxxxxxx.net/hprofile-ak-ash2/xxxxxx.jpg" alt=""></a><div class="clearfix _42ef"><div class="_6a rfloat"><div class="_6a _6b" style="height:50px"></div><div class="_6a _6b"><div class="_5t4x"><div class="FriendButton" id="u_2h_1w"><button class="_42ft _4jy0 FriendRequestAdd addButton _4jy3 _517h" type="button">

我想得到“https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser

我尝试了什么

from bs4 import BeautifulSoup
html = open('full_page_firefox.html')
def getLinks(html):
    soup = BeautifulSoup(html)
    anchors = soup.findAll('a')
    links = []
    for a in anchors:
        links.append(a['href'])
    return links
print getLinks(html)

拆分似乎也不起作用,因为它不保留模式。因此,如果我使用诸如“https://www.facebook.com/*.$”之类的东西来获取带有 re.split() 或其他东西的 url,它就不起作用了。

【问题讨论】:

标签: python regex url


【解决方案1】:

你的代码在这里工作,检查你的输入文件,确保漂亮的肥皂可以解析它。

顺便说一句,也可以考虑使用 lxml

from lxml import etree
print etree.parse('full_page_firefox.html').xpath('//a/@href | //img/@src')

['https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser', 
'https://fbcdn-profile-xxxxxxxx.net/hprofile-ak-ash2/xxxxxx.jpg']

【讨论】:

    【解决方案2】:

    您的功能有效。我将您提供的那段 html 复制到了一个 html 文件中,并添加了 &lt;html&gt;&lt;body&gt; 标记,以防万一。

    然后我尝试了:

    with open('C:/users/brian/desktop/html.html') as html:
        print getLinks(html)
    

    在python解释器中得到如下输出:

    [u'https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser']
    

    拨打str就可以了

    【讨论】:

      【解决方案3】:

      你可以通过该模式检查 url,在被 BS 解析后,如下所示:

      from bs4 import BeautifulSoup
      import re
      html = open('full_page_firefox.html')
      def getLinks(html):
          soup = BeautifulSoup(html)
          anchors = soup.findAll('a')
          links = []
          for a in anchors:
              match_result = re.match(r'https://www.facebook.com/.*$', a['href'])
              if match_result is not None:
                  links.append(match_result.string)
          return links
      print getLinks(html)
      

      注意: 1.'/'和'.'之间没有空格 2.'$'匹配字符串结尾,慎用

      【讨论】:

        猜你喜欢
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 2010-10-28
        • 2011-01-26
        • 1970-01-01
        • 2018-11-14
        相关资源
        最近更新 更多