【问题标题】:cleaning strings for link urls in python在 python 中清理链接 url 的字符串
【发布时间】:2015-05-09 06:42:56
【问题描述】:

所以我有漂亮的汤代码,可以访问网站的主页 并刮掉那里的链接。但是,当我在 python 中获取链接时,我似乎无法清理链接(在将其转换为字符串之后)以与根 url 连接。

import re
import requests
import bs4

list1=[]

def get_links():

    regex3= re.compile('/[a-z\-]+/[a-z\-]+')
    response = requests.get('http://noisetrade.com')
    soup = bs4.BeautifulSoup(response.text)
    links=  soup.select('div.grid_info  a[href]')
    for link in links:
       lk= link.get('href')
       prtLk= regex3.findall(lk)
       list1.append(prtLk)


def visit_pages():
    url1=str(list1[1])
    print(url)

get_links()
visit_pages()

产生输出:“['/stevevantinemusic/unsolicited-material']”

期望的输出:“/stevevantinemusic/unsolicited-material”

我已经尝试过 .strip() 和 .replace() 以及 re.sub/match/etc。 . .我似乎无法隔离我需要删除的字符 '[,\',]',我已经使用子字符串对其进行了迭代,但这感觉效率低下。我确定我遗漏了一些明显的东西。

【问题讨论】:

    标签: python regex web-scraping beautifulsoup python-requests


    【解决方案1】:

    这是我认为您正在尝试做的一个示例:

    >>> import bs4
    >>> with open('noise.html', 'r') as f:
    ...     lines = f.read()
    ... 
    >>> soup = bs4.BeautifulSoup(lines)
    >>> root_url = 'http://noisetrade.com'
    >>> for link in soup.select('div.grid_info a[href]'):
    ...     print(root_url + link.get('href'))
    ... 
    http://noisetrade.com/stevevantinemusic
    http://noisetrade.com/stevevantinemusic/unsolicited-material
    http://noisetrade.com/jessicarotter
    http://noisetrade.com/jessicarotter/winter-sun
    http://noisetrade.com/geographermusic
    http://noisetrade.com/geographermusic/live-from-the-el-rey-theatre
    http://noisetrade.com/kaleo
    http://noisetrade.com/kaleo/all-the-pretty-girls-ep
    http://noisetrade.com/aviddancer
    http://noisetrade.com/aviddancer/an-introduction
    http://noisetrade.com/thinkr
    http://noisetrade.com/thinkr/quiet-kids-ep
    http://noisetrade.com/timcaffeemusic
    http://noisetrade.com/timcaffeemusic/from-conversations
    http://noisetrade.com/pearl
    http://noisetrade.com/pearl/hello
    http://noisetrade.com/staceyrandolmusic
    http://noisetrade.com/staceyrandolmusic/fables-noisetrade-sampler
    http://noisetrade.com/sleepyholler
    http://noisetrade.com/sleepyholler/sleepy-holler
    http://noisetrade.com/sarahmcgowanmusic
    http://noisetrade.com/sarahmcgowanmusic/indian-summer
    http://noisetrade.com/briandunne
    http://noisetrade.com/briandunne/songs-from-the-hive
    

    请记住,bs4 也有它自己使用的类型。

    调试脚本的一个好方法是放置:

    for link in links:
       import pdb;pdb.set_trace() # the script will stop for debugging here
       lk= link.get('href')
       prtLk= regex3.findall(lk)
       list1.append(prtLk)
    

    任何你想调试的地方。

    然后你可以在pdb 中做这样的事情:

    next
    l
    print(type(lk))
    print(links)
    dir()
    dir(links)
    dir(lk)
    

    【讨论】:

    • 另外,pdb 是 c++ 中 gdb 的 python 等价物。
    【解决方案2】:

    findall 返回结果列表,因此您可以编写:

    for link in links:
        lk = link.get('href')    
        urls = regex3.findall(lk)   
        if urls:
            prtLk = urls[0]
            list1.append(prtLk)
    

    或者更好,使用search方法:

    for link in links:
        lk = link.get('href')    
        m = regex3.search(lk)
        if m:
            prtLk = m.group()
            list1.append(prtLk)
    

    这些括号是将具有一个元素的列表转换为字符串的结果。 例如:

    l = ['text']
    str(l)
    

    结果:

    "['text']"
    

    【讨论】:

      【解决方案3】:

      这里我使用正则表达式r'[\[\'\]]' 将任何不需要的字符替换为空字符串:

      $ cat pw.py
      import re
      
      def visit_pages():
          url1="['/stevevantinemusic/unsolicited-material']"
          url1 = re.sub(r'[\[\'\]]','',url1)
          print(url1)
      
      visit_pages()
      
      $ python pw.py
      /stevevantinemusic/unsolicited-material
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 2014-05-22
        • 2021-02-16
        相关资源
        最近更新 更多