【问题标题】:How can I make urllib use the link it has found?如何让 urllib 使用它找到的链接?
【发布时间】:2017-02-17 23:30:16
【问题描述】:

在 raw_input 中使用此链接:http://edition.cnn.com/

import urllib
import re


CNN_Technology = (raw_input('Paste your link here: '))

urls = ["http://edition.cnn.com/"]
pattern = 'Entertainment</a><a class="nav-menu-links__link" href="//(.+?)data-analytics-header="main-menu_tech'
result = re.compile(pattern)

for url in urls:
    htmlsource = urllib.urlopen(url)
    htmltext = htmlsource.read()
    cnntech = re.findall(result, htmltext)
    print ""
    print "CNN Link:"
    print cnntech
    print ""

我希望新找到的链接 money.cnn.com/technology/ 位于 cnntech 所在的位置,然后扫描它。

urls = ["cnntech"] 
pattern = 'Entertainment</a><a class="nav-menu-links__link" href="//(.+?)data-analytics-header="main-menu_tech'
result = re.compile(pattern)

for url in urls:
    htmlsource = urllib.urlopen(url)
    htmltext = htmlsource.read()
    cnntech2 = re.findall(result, htmltext)
    print "CNN Link:"
    print cnntech2
<code>

【问题讨论】:

  • 尝试用正则表达式提取 HTML 片段是……怎么说? A controversial topic。但是试图用一个由 HTML 标签组成的正则表达式来提取一个精确的链接是非常疯狂的。您肯定需要学习如何使用 html 解析库,例如 BeautifulSoup。

标签: python python-2.7 web-scraping urllib


【解决方案1】:

好吧,让我们想象一下,正则表达式是解析 HTML 的绝佳方式。 所以我们身处科幻世界。

您的第一个脚本的输出如下所示:['money.cnn.com/technology/" ']

这是一个包含错误链接的列表:http:// 协议未指定,末尾有引号。 Urllib 对此无能为力。

首先要做的是修复你的正则表达式以获得最正确的 URL:

pattern = 'Entertainment</a><a class="nav-menu-links__link" href="//(.+?)" data-analytics-header="main-menu_tech'

现在,将前缀“http://”添加到 cnntech 列表中的所有网址:

urls = []
for links in cnntech:
    urls.append("http://" + links)

最后,你可以试试脚本的第二部分:

pattern = YOURSECONDREGEGEX #I do not understand what you want to extract
result = re.compile(pattern)

for url in urls:
    html = urllib.urlopen(url).read()
    cnntech2 = re.findall(result, str(html))
    print "CNN Link:", cnntech2, "\ n"

现在,用同样的例子回到现实世界,但这次使用 HTML 解析器,如 Pyquery。

import requests #better than urllib
from pyquery import PyQuery as pq

urls = ["http://edition.cnn.com/"]

for url in urls:
    response = requests.get(url)
    doc = pq(response.content)
    cnntech = doc('.m-footer__subtitles--money .m-footer__list-item:nth-child(3) .m-footer__link').attr('href')
    print("CNN Link: ", cnntech)

输出:

CNN Link:  http://money.cnn.com/technology/

奇怪的字符串'.m-footer__subtitles--money .m-footer__list-item:nth-child(3) .m-footer__link' 是一个CSS 选择器。乍一看,它似乎比正则表达式更可怕,但它却简单得多。您可以使用 Google Chrome 的Selector gadget 等工具轻松找到它。

【讨论】:

  • 感谢您的帮助。试过你的回答后,我会看看beautifulsoup。
  • @Pythor 不客气。我已经用一个使用 Pyquery 的脚本示例更新了答案,其原理与 BeautifulSoup 非常相似。
  • 谢谢你的帮助。我马上就开始研究beautifulsoup
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多