2017-02-19 31 views
1

我正在使用BeautifulSoup来创建帖子和相关链接的论坛页面。将一个字符串添加到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

希望得到一些正确的语法帮助,将prepended字符串连接到输出。

谢谢。

回答

0

这会为你工作: -

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']) 
+0

谢谢,感谢。 – runDiomedes

+0

@runDiomedes如果你认为它适合你,你应该接受它通过点击右键button.Thanks! –

0

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

店基地网址:

xx = 'base_url' 

您的打印线是:

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

其中{}得到由.format更换,而不是有你送入参数变量。

+0

辉煌,谢谢。一旦孩子睡觉,我会给它一个旋转! – runDiomedes

+0

Np,让我知道它是怎么回事。 =) –

相关问题