如何使urllib使用找到的链接?

2024-03-29 14:56:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在原始输入中使用此链接: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>

Tags: recomurllinkresulturlliburlscnn
1条回答
网友
1楼 · 发布于 2024-03-29 14:56:16

好吧,让我们设想一下regex是解析HTML的一种非常好的方法。所以我们身处科幻世界。

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

这是一个包含坏链接的列表:没有指定http://协议,并且在末尾有一个引号。Urllib对此无能为力。你知道吗

首先要做的是修复regex,以便获得最正确的URL:

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

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

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选择器。乍一看,它似乎比正则表达式更可怕,但它要简单得多。你可以使用googlechrome的Selector gadget等工具轻松找到它。你知道吗

相关问题 更多 >