如何让 urllib 使用它找到的 link?

How can I make urllib use the link it has found?

在 raw_input 中使用此 link: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 ""

我希望新找到的linkmoney.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。 所以我们处于 sci-fi 的世界。

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

这是一个包含错误 link 的列表:未指定 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 等工具轻松找到它。