【发布时间】:2016-11-11 07:32:49
【问题描述】:
【问题讨论】:
标签: python python-3.x web-crawler urllib
【问题讨论】:
标签: python python-3.x web-crawler urllib
您应该使用漂亮的汤来代替它,它可以根据您的要求非常顺利地工作。下面我举个例子:
from bs4 import BeautifulSoup
import requests
def links(url):
html = requests.get(url).content
bsObj = BeautifulSoup(html, 'lxml')
links = bsObj.findAll('a')
finalLinks = set()
for link in links:
finalLinks.add(link.attrs['href'])
【讨论】:
试试这个
导入 urllib.request
重新导入
#传递任意url url = "Want to get all links in a webpage using urllib.request"
urllist = re.findall(r"""
打印(urllist)
【讨论】:
这是另一个解决方案:
from urllib.request import urlopen
url = ''
html = str(urlopen(url).read())
for i in range(len(html) - 3):
if html[i] == '<' and html[i+1] == 'a' and html[i+2] == ' ':
pos = html[i:].find('</a>')
print(html[i: i+pos+4])
定义您的网址。 希望这会有所帮助,不要忘记投票并接受。
【讨论】:
其中一种解决方案怎么样?
import requests
from bs4 import BeautifulSoup
research_later = "giraffe"
goog_search = "https://www.google.co.uk/search?sclient=psy-ab&client=ubuntu&hs=k5b&channel=fs&biw=1366&bih=648&noj=1&q=" + research_later
r = requests.get(goog_search)
print r
soup = BeautifulSoup(r.text, "html.parser")
print soup
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.flashscore.com/soccer/netherlands/eredivisie/results/")
soup = BeautifulSoup(r.content)
htmltext = soup.prettify()
print htmltext
import sys,requests,csv,io
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url = "http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings"
r = requests.get(url)
r.content
soup = BeautifulSoup(r.content, "html.parser")
maindiv = soup.find_all("div", {"class": "text-center"})
for div in maindiv:
print(div.text)
【讨论】:
有时 BeautifulSoup 和 requests 不是您想要使用的。
在某些情况下,当使用请求库时,相关网站可能会阻止您抓取(得到响应 403)。所以你必须使用 urllib.request 代替。
您可以通过以下方式获取您尝试使用 urllib.request 抓取的网页上列出的所有链接 (href)。
import urllib.request
from urllib.request import urlretrieve, Request, urlopen
import re
# get full html code from a website
response = Request('https://www.your_url.com', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(response)
print(webpage.read())
# create a list of all links/href tags
url = 'https://www.your_url.com'
urllist = re.findall("href=[\"\'](.*?)[\"\']", urllib.request.urlopen(url).read().decode("utf-8"))
print(urllist)
# print each link on a seperate line
for elem in urllist:
print(elem)
在代码中,我们使用带有所选明文编码 x 的 str.decode(x) 将 HTML 对象转换为明文字符串。标准编码是 utf-8。如果您尝试抓取的网站使用不同的编码,您可能需要更改编码。
我们在正则表达式的帮助下找到链接:在明文字符串上使用正则表达式模式 href=\"\'[\"\'] 调用 re.findall(pattern,string) 以匹配所有 href 标签,但仅提取引号中的 url 文本以返回包含在 href 标记内的链接列表。
【讨论】:
用 request-html 试试吧,它可以解析 HTML 并且我们可以搜索 HTML 中的任何标签、覆层或 ID
from requests_html import HTMLSession
session = HTMLSession()
r = session.get(url)
r.html.links
如果你想要绝对链接使用
r.html.absolute_links
【讨论】: