【问题标题】:Prepending a string to the output of a BeautifulSoup scrape将字符串添加到 BeautifulSoup 抓取的输出中
【发布时间】:2017-02-19 00:14:21
【问题描述】:

我正在使用 BeautifulSoup 抓取论坛页面以获取帖子和相关链接。

我想要的页面上的链接格式为r"xx/res/[0-9]{5}.html$"

到目前为止,在我的 BeautifulSoup 对象中找到它们非常好,当我 print 时返回以下链接格式:/xx/res/83071.html。

我现在想在每个结果前面加上域名“http://website.com”,并使用完整的 url 作为进一步抓取的基础。

我的成功代码如下所示:

url = 'http://website.com/xx/index.html'
res = urlopen(url)
soup = BeautifulSoup(res, 'html.parser')

links = soup.select('a',{'href':re.compile(r"xx/res/[0-9]{5}.html$")})

for l in links:
    print(l['href'])

例如,以下内容被打印到控制台:

  • /xx/res/83071.html
  • /xx/res/81813.html
  • /xx/res/92014.html
  • /xx/res/92393.html

希望获得有关正确语法的帮助,以将前置字符串连接到输出。

谢谢。

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    这对你有用:-

    url = 'http://website.com/xx/index.html'
    res = urlopen(url)
    soup = BeautifulSoup(res, 'html.parser')
    
    links = soup.select('a',{'href':re.compile(r"xx/res/[0-9]{5}.html$")})
    
    for l in links:
        print ('http://website.com'+l['href'])
    

    【讨论】:

    • 谢谢,不胜感激。
    • @runDiomedes 如果你认为它适合你,你应该点击右键接受它。谢谢!!
    【解决方案2】:

    有几种方法可以做到这一点。我个人喜欢 string.format 方法。

    存储基本网址:

    xx = 'base_url'
    

    您的打印行将是:

    print('/{}/{}'.format(xx, l['href']))
    

    其中 {} 被替换为 .format 以将您提供给参数的变量代替。

    【讨论】:

    • 太棒了,谢谢。一旦孩子上床睡觉,我会试一试!
    • Np,让我知道进展如何。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多