Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从列表python 2.7中提取特定元素_Python_Python 2.7_List_Extract - Fatal编程技术网

从列表python 2.7中提取特定元素

从列表python 2.7中提取特定元素,python,python-2.7,list,extract,Python,Python 2.7,List,Extract,我正在开发一个从特定页面提取URL的机器人。我已经提取了所有链接并将它们放在一个列表中,现在我似乎无法从列表中获取现实主义URL(指向以http或https开头的其他站点)并将它们附加到另一个列表中,或者删除那些不以http开头的。提前谢谢 import urllib2 import requests from bs4 import BeautifulSoup def main(): #get all the links from bing about cancer site

我正在开发一个从特定页面提取URL的机器人。我已经提取了所有链接并将它们放在一个列表中,现在我似乎无法从列表中获取现实主义URL(指向以http或https开头的其他站点)并将它们附加到另一个列表中,或者删除那些不以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()

您可以使用
urlparse.urljoin

link = urlparse.urljoin(site, link.get("href"))
这将从相对URL中创建绝对URL


您还应该使用
html\u content=r.text
而不是
html\u content=r.content
r.text
负责使用正确的编码。

您可以使用
urlparse.urljoin

link = urlparse.urljoin(site, link.get("href"))
这将从相对URL中创建绝对URL


您还应该使用
html\u content=r.text
而不是
html\u content=r.content
r.text
注意使用正确的编码。

您能详细说明这个问题吗?如果我按照编写的方式运行您的代码,
url
将填充一个URL列表,其中许多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“,…”
)你能解释一下你得到的结果与你想要的结果有何不同吗?我想要指向实际站点的链接,而不是脚本或样式表(例如,我不想/script.js或/styles.cscan您可以详细说明这个问题吗?如果我按编写的方式运行代码,
URL
将填充一个URL列表,其中许多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“,…”
)你能解释一下你得到的结果与你想要的结果有何不同吗?我想要指向实际站点的链接,而不是脚本或样式表(例如我不想要/script.js或/styles.css)