在python 2.7中分割线条

时间:2014-02-11 00:40:14

标签: python python-2.7 xgoogle

我需要附上以下声明:

from xgoogle.search import GoogleSearch, SearchError
import urllib
import re
import random
import json as m_json

claves = open("robot/palabras_claves.txt")
listado_claves = claves.read()
nuevo_listado_claves = listado_claves.split("\n")

query = nuevo_listado_claves
query = urllib.urlencode ( { 'q' : query } )
response = urllib.urlopen ( 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&' + query ).read()
json = m_json.loads ( response )
results = json [ 'responseData' ] [ 'results' ]

for result in results:
    title = result['title']
    url = result['url']   
    print url

OUT:

htt://www.myweb0.com
htt://www.myweb1.com
htt://www.myweb2.com
htt://www.myweb3.com

现在转换器网址:

a = ["htt://www.myweb0.com", 
     "htt://www.myweb1.com", 
     "htt://www.myweb2.com",
     "htt://www.myweb3.com", 
     "...."]

print(random.choice([a]))

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

import json
import random
import requests

KEYWORD_FILE = "robot/palabras_claves.txt"
SEARCH_URL   = "http://ajax.googleapis.com/ajax/services/search/web"

def get_lines(fname):
    with open(fname) as inf:
        return inf.read().splitlines()    # no trailing newlines

def main():
    keywords = get_lines(KEYWORD_FILE)

    for kw in keywords:
        # get search results for this keyword
        resp = requests.get(SEARCH_URL, params={'v':'1.0', 'q':kw})
        data = json.loads(resp.content)
        results = data['responseData']['results']

        # reduce to [(title,url), ...]
        pages = [(res['title'], res['url']) for res in results]

        # print random url for this keyword
        print(random.choice(pages)[1])

if __name__=="__main__":
    main()