如何使用python收集一组连续的网页?
How to collect a continuous set of webpages using python?
这里,x是一个范围从1到200000的数字。我想运行一个循环来获取所有的URL,然后使用漂亮的URL从每个URL中提取内容汤。
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
content = urlopen(re.compile(r"https://example.net/users/[0-9]//"))
soup = BeautifulSoup(content)
这是正确的方法吗?我必须执行两件事。
- 得到一组连续的URLs
- 从每个 page/URL.
中提取并存储检索到的内容
更新:
我只能从每个网页中获取一个特定值。
soup = BeautifulSoup(content)
divTag = soup.find_all("div", {"class":"classname"})
for tag in divTag:
ulTags = tag.find_all("ul", {"class":"classname"})
for tag in ulTags:
aTags = tag.find_all("a",{"class":"classname"})
for tag in aTags:
name = tag.find('img')['alt']
print(name)
如果您只需要网页的内容,您可能会使用 lxml
,您可以从中解析内容。类似于:
from lxml import etree
r = requests.get('https://example.net/users/x')
dom = etree.fromstring(r.text)
# parse seomthing
title = dom.xpath('//h1[@class="title"]')[0].text
此外,如果您正在抓取数千个页面的 10 或 100 个页面,您可能需要查看类似 grequests 的内容,您可以在其中执行多个异步 HTTP 请求。
你可以试试这个:
import urllib2
import shutil
urls = []
for i in range(10):
urls.append(str('https://www.example.org/users/' + i))
def getUrl(urls):
for url in urls:
# Only a file_name based on url string
file_name = url.replace('https://', '').replace('.', '_').replace('/', '_')
response = urllib2.urlopen(url)
with open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
getUrl(urls)
这里,x是一个范围从1到200000的数字。我想运行一个循环来获取所有的URL,然后使用漂亮的URL从每个URL中提取内容汤。
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
content = urlopen(re.compile(r"https://example.net/users/[0-9]//"))
soup = BeautifulSoup(content)
这是正确的方法吗?我必须执行两件事。
- 得到一组连续的URLs
- 从每个 page/URL. 中提取并存储检索到的内容
更新:
我只能从每个网页中获取一个特定值。
soup = BeautifulSoup(content)
divTag = soup.find_all("div", {"class":"classname"})
for tag in divTag:
ulTags = tag.find_all("ul", {"class":"classname"})
for tag in ulTags:
aTags = tag.find_all("a",{"class":"classname"})
for tag in aTags:
name = tag.find('img')['alt']
print(name)
如果您只需要网页的内容,您可能会使用 lxml
,您可以从中解析内容。类似于:
from lxml import etree
r = requests.get('https://example.net/users/x')
dom = etree.fromstring(r.text)
# parse seomthing
title = dom.xpath('//h1[@class="title"]')[0].text
此外,如果您正在抓取数千个页面的 10 或 100 个页面,您可能需要查看类似 grequests 的内容,您可以在其中执行多个异步 HTTP 请求。
你可以试试这个:
import urllib2
import shutil
urls = []
for i in range(10):
urls.append(str('https://www.example.org/users/' + i))
def getUrl(urls):
for url in urls:
# Only a file_name based on url string
file_name = url.replace('https://', '').replace('.', '_').replace('/', '_')
response = urllib2.urlopen(url)
with open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
getUrl(urls)