【问题标题】:Extracting href links from within website source w/ Python使用 Python 从网站源中提取 href 链接
【发布时间】:2015-11-24 15:10:30
【问题描述】:

我之前问过这个问题无济于事。我试图弄清楚如何实现 bs4 来获取用于从网站源中下载的链接。我无法弄清楚的问题是链接在动态内容库中。 之前的html sn-p我已经去掉了,看下面

只有在手动从网站抓取源代码后,我们才能使用此脚本抓取链接:

import re
enter code here

line = line.rstrip()
x = re.findall('href=[\'"]?([^\'" >]+)tif', line)
if len(x) > 0 :
    result.write('tif">link</a><br>\n<a href="'.join(x))

 `result.write('tif">link</a><br>\n\n</html>\n</body>\n')

result.write("There are " + len(x) + " links")       


print "Download HTML page created."

但只有在进入网站后 ctrl + a -> 查看源代码 -> 全选 & 复制 -> 粘贴到 SourceCode.txt 上。我想从这一切中消除体力劳动。

非常感谢任何信息/提示/建议!

编辑

我想添加一些关于我们正在使用的网站的更多信息,图书馆内容只有在手动展开时才会显示。否则,内容(即下载链接/href *.tif)不可见。这是我们看到的一个例子:

未打开库元素的站点源代码。

<html><body>

打开库元素后的源代码。

<html><body>
<h3>Library</h3>
<div id="libraryModalBody">

    <div><table><tbody>

    <tr>
    <td>Tile12</td>
    <td><a href="http://www.website.com/path/Tile12.zip">Button</a></td>
    </tr>

    </tbody></table></div>

</div> 

扩展所有下载选项后的源代码。

<html><body>
<h3>Library</h3>
<div id="libraryModalBody">
    <div><table><tbody>
    <tr>
    <td>Tile12</td>
    <td><a href="http://www.website.com/path/Tile12.zip">Button</a></td>
    </tr>
    <tr>
    <td>Tile12_Set1.tif</td>
    <td><a href="http://www.website.com/path/Tile12_Set1.tif">Button</a></td>
    </tr>
    <tr>
    <td>Tile12_Set2.tif</td>
    <td><a href="http://www.website.com/path/Tile12_Set2.tif">Button</a></td>
    </tr>
    </tbody></table></div>
</div>

我们的最终目标是只需输入网站 url 即可获取下载链接。问题似乎在于内容的显示方式(即动态内容仅在手动扩展库后可见。

【问题讨论】:

    标签: python html beautifulsoup data-extraction


    【解决方案1】:

    不要尝试使用正则表达式解析 HTML。 It's not possibleit won't work。改用 BeautifulSoup4:

    from urllib2 import urlopen
    from bs4 import BeautifulSoup
    
    url = "http://www.your-server.com/page.html"
    document = urlopen(url)
    soup = BeautifulSoup(document)
    
    # look for all URLs:
    found_urls = [link["href"] for link in soup.find_all("a", href=True)]
    
    # look only for URLs to *.tif files:
    found_tif_urls = [link["href"] for link in soup.find_all("a", href=True) if link["href"].endswith(".tif")]
    

    【讨论】:

    • 谢谢geckon,这个问题。我可能不正确地理解您的脚本,但这可以通过从网站手动检索 html 源代码来实现。如果是这样,这并没有消除我已经在做的体力劳动。
    • 有道理,感谢您提供的信息。奇怪的是,正则表达式一直在为我一直在做的事情工作。话虽如此,我会使用你写的。谢谢
    • @D.V 正则表达式可能适用于某些 HTML 示例,但有些 HTML 源代码不适用于它们。我的回答现在解决你的问题了吗?
    • 您的回答肯定让我们深入了解我们正在使用的正则表达式可能存在的缺陷。我将尝试您的示例并发布结果。我非常感谢您的及时回答!
    • 我一直在玩你的例子,我必须解决我的 bs4 导入问题(这给了我 html 解析的问题)。无论哪种情况,感谢您的帮助。
    【解决方案2】:

    您不妨看看PyQuery 库,它使用来自 JQuery 的 CSS 选择器(子)集:

    pq = PyQuery(body)
    pq('div.content div#filter-container div.filter-section')
    

    【讨论】:

    • 谢谢,Ojomio。我会测试你的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2021-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多