【问题标题】:Extracting specific elements from list python 2.7从列表python 2.7中提取特定元素
【发布时间】:2017-03-18 23:30:27
【问题描述】:

我正在开发这个从特定页面提取网址的机器人。我已经提取了所有链接并将它们放在一个列表中我似乎无法从列表中获取现实主义的 url(导致以 http 或 https 开头的其他站点)并将它们附加到另一个列表或删除那些不t 以 http 开头。提前致谢

import urllib2
import requests
from bs4 import BeautifulSoup

def main():
    #get all the links from bing about cancer
    site = "http://www.bing.com/search?q=cancer&qs=n&form=QBLH&pq=cancer&sc=8-4&sp=-1&sk=&cvid=E56491F36028416EB41694212B7C33F2"
    urls =[]
    true_links = []
    r = requests.get(site)
    html_content = r.content
    soup = BeautifulSoup(html_content, 'html.parser')
    links = soup.find_all("a")
    for link in links:
        link = link.get("href")
        urls.append(str(link))
        #urls.append(link.get("href"))

    #print map(str, urls)
    #REMOVE GARBAGE LINKS

    print len(urls)
    print urls

main()

【问题讨论】:

  • 你能详细说明问题吗?如果我按照编写的代码运行您的代码,urls 会填充一个 URL 列表,其中许多指向 bing 以外的站点(例如,...'http://www.coursera.org/course/clinicaltrials', 'http://www.coursera.org/course/clinicaltrials', 'http://www.khanacademy.org/science/health-and-medicine/respiratory-system-diseases/lung-cancer/v/lung-cancer-complications',...)您能解释一下您得到的结果与结果有何不同吗你想要吗?
  • 我想要指向实际站点的链接,而不是脚本或样式表(例如,我想要 webmd.com/cancer/default.htm 而不是 /script.js 或 /styles.css

标签: python python-2.7 list extract


【解决方案1】:

你可以使用urlparse.urljoin:

link = urlparse.urljoin(site, link.get("href"))

这将从相对 URL 中创建绝对 URL。

您还应该使用html_content = r.text 而不是html_content = r.contentr.text 负责使用正确的编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多