【问题标题】:How do I scrape a url from html when href is a file directory当href是文件目录时,如何从html中抓取url
【发布时间】:2020-05-27 22:52:32
【问题描述】:

我对网络抓取非常陌生。我正在尝试从网页中提取 URL 列表,但 href 包含目录而不是 url。有没有办法获取 URL?

我的代码:

url='https://www.goodreads.com/shelf/show/bestsellers'
elements = requests.get(url).text

soup = BeautifulSoup(elements, "html.parser")
for link in soup.findAll('a',attrs={'class':"leftAlignedImage"}):
    print (link['href'])

输出:

/book/show/5060378-the-girl-who-played-with-fire
/book/show/968.The_Da_Vinci_Code
/book/show/4667024-the-help
/book/show/2429135.The_Girl_with_the_Dragon_Tattoo
...

【问题讨论】:

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


    【解决方案1】:

    这更像是对 OP (@adib) 的评论,而不是答案。您的方法对我来说看起来不错,但您可以通过在开始时将 URL 分成两部分来避免使用replace

    from bs4 import BeautifulSoup
    import requests
    
    baseUrl = 'https://www.goodreads.com'
    path = '/shelf/show/bestsellers'
    page = requests.get(baseUrl + path)
    
    soup = BeautifulSoup(page.text, "html.parser")
    for link in soup.findAll('a',attrs={'class':"leftAlignedImage"}):
        print (baseUrl + link['href'])
    

    这将为您提供如下结果:

    https://www.goodreads.com/book/show/5060378-the-girl-who-played-with-fire
    https://www.goodreads.com/book/show/968.The_Da_Vinci_Code
    https://www.goodreads.com/book/show/4667024-the-help
    

    【讨论】:

    • 当整个 URL 未被捕获时,这是更常见的连接方式
    【解决方案2】:

    用替换解决了它,我不确定是否有更好的解决方案。

    print(link['href'].replace('/book/show/','https://www.goodreads.com/book/show/'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多