2024-08-16



import tkinter as tk
import requests
from bs4 import BeautifulSoup
 
def fetch_quotes(symbol):
    url = f"https://finance.yahoo.com/quote/{symbol}"
    response = requests.get(url)
    if response.ok:
        soup = BeautifulSoup(response.text, 'html.parser')
        name = soup.find(id='quote-header-info').find('h1').text
        price = soup.find(class_='My<span class="katex">\(b\)</span>').text
        return f"{name} - {price}"
    else:
        return "Error fetching quote"
 
def update_quote(symbol):
    quote = fetch_quotes(symbol.get())
    quote_label.config(text=quote)
 
root = tk.Tk()
root.title("Yahoo Finance Stock Quote Fetcher")
root.geometry("400x200")
 
symbol_label = tk.Label(root, text="Enter stock symbol:")
symbol_label.pack()
 
symbol_entry = tk.Entry(root)
symbol_entry.pack()
 
fetch_button = tk.Button(root, text="Fetch Quote", command=lambda: update_quote(symbol_entry))
fetch_button.pack()
 
quote_label = tk.Label(root, text="")
quote_label.pack()
 
root.mainloop()

这段代码使用了tkinter库来创建一个简单的用户界面,允许用户输入股票代码,并在点击按钮后获取该股票的名称和价格。这个例子教会了如何将爬虫逻辑集成到图形用户界面中,并展示了如何使用Python进行简单的GUI编程。

2024-08-16

爬虫是一种自动提取网页数据的程序,用于数据采集。它可以帮助我们快速获取大量的信息,但同时也有可能触犯网站的反爬机制,导致被封号甚至法律问题。

  1. 安装requests和BeautifulSoup库



pip install requests
pip install beautifulsoup4
  1. 简单的爬虫示例



import requests
from bs4 import BeautifulSoup
 
url = 'http://example.com'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
 
for link in soup.find_all('a'):
    print(link.get('href'))

这个例子中,我们使用requests库获取了网页内容,然后用BeautifulSoup进行解析,找出所有的a标签的href属性,也就是链接。

  1. 反爬虫策略

网站可能会通过各种方式阻止爬虫,如JavaScript动态渲染、Cookies验证、IP封禁等。

  1. 处理JavaScript渲染的页面

对于现今许多网站使用JavaScript动态渲染的情况,可以使用Selenium或者Pyppeteer等工具来处理。

  1. 使用代理和设置请求头



proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:3128',
}
 
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
}
 
response = requests.get('http://example.com', headers=headers, proxies=proxies)
  1. 应对反爬策略

如果网站设置了复杂的反爬机制,可以尝试以下策略:

  • 使用代理轮换IP
  • 限制爬取速度
  • 使用用户代理(User-Agent)来模拟不同的浏览器访问
  • 使用登录认证
  1. 爬虫与法律

遵守网站的robots.txt协议,不爬取不允许爬取的页面。未授权获取数据时,应确保你有权限获取数据,并遵守相关的法律法规。

以上是爬虫入门的基本概念和策略,实际应用中可能需要根据具体网站的反爬策略来调整策略和代码。

2024-08-16



import requests
from lxml import etree
 
class TianMaoSpider:
    def __init__(self, keyword, page_num):
        self.keyword = keyword
        self.page_num = page_num
        self.base_url = "https://s.taobao.com/search?q="
 
    def get_response(self, url):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
 
    def parse_page(self, page_url):
        html = self.get_response(page_url)
        if html:
            parser = etree.HTML(html)
            items = parser.xpath('//div[@class="item J_MouserOnverReq  "]')
            for item in items:
                title = item.xpath('.//div[@class="title"]/a/text()')[0]
                price = item.xpath('.//div[@class="price"]/strong/text()')[0]
                print(f"商品名称: {title}, 价格: {price}")
 
    def run(self):
        for page in range(1, self.page_num + 1):
            page_url = f"{self.base_url}{self.keyword}&s={(page-1)*44}"
            self.parse_page(page_url)
 
if __name__ == "__main__":
    spider = TianMaoSpider("口罩", 2)
    spider.run()

这段代码实现了一个简单的天猫商品数据爬虫。首先定义了一个TianMaoSpider类,包含初始化方法、获取响应、解析页面和运行爬虫的方法。在__init__方法中,设置了搜索关键词和需要爬取的页数。get_response方法用于发送请求并获取响应。parse_page方法解析页面,提取商品标题和价格,并打印输出。最后,在run方法中通过循环遍历页面,并调用parse_page方法来爬取数据。这个简单的爬虫示例教会了如何使用Python进行基本的网页爬取。

2024-08-16

为了模拟登录,你需要使用Python的requests库来发送HTTP请求,并处理cookies和session对象。以下是一个模拟登录的基本例子:




import requests
 
# 登录的URL
login_url = 'http://example.com/login'
 
# 创建一个Session对象,以便能够保持会话状态
session = requests.Session()
 
# 登录需要的参数,比如用户名和密码
login_params = {
    'username': 'your_username',
    'password': 'your_password'
}
 
# 发送POST请求进行登录
response = session.post(login_url, data=login_params)
 
# 检查是否登录成功
if response.ok:
    print('登录成功')
    # 登录成功后,可以继续使用session对象来发送后续请求
    # 例如获取用户的个人信息
    user_url = 'http://example.com/user'
    user_response = session.get(user_url)
    if user_response.ok:
        print('用户信息:', user_response.text)
    else:
        print('获取用户信息失败')
else:
    print('登录失败')

请注意,实际的登录可能涉及到处理cookies、CSRF tokens、headers等安全措施,可能需要你手动处理或者使用专门的库来帮助你完成。上面的代码只是一个简单的例子,实际使用时需要根据目标网站的具体情况进行调整。

2024-08-16



import requests
from bs4 import BeautifulSoup
import time
import random
import csv
 
def get_html(url, headers):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except requests.RequestException:
        return None
 
def parse_html(html, keyword):
    soup = BeautifulSoup(html, 'lxml')
    news_list = soup.select('div.news-box > ul > li > a')
    for news in news_list:
        title = news.select_one('h3').text
        if keyword.lower() in title.lower():
            url = news['href']
            print(f'正在爬取新闻: {title}')
            yield url
 
def get_news_detail(url, headers):
    html = get_html(url, headers)
    soup = BeautifulSoup(html, 'lxml')
    content = soup.select_one('div.article-content').text
    return content
 
def save_to_csv(data, filename):
    with open(filename, 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(data)
 
def main(keyword):
    base_url = 'https://news.sina.com.cn/china/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Cookie': 'your_cookie_here'
    }
    filename = f'{keyword}_news.csv'
    for url in parse_html(get_html(base_url, headers), keyword):
        content = get_news_detail(url, headers)
        save_to_csv([url, content], filename)
        time.sleep(random.uniform(1, 3))  # 添加随机等待防止被封禁IP
 
if __name__ == '__main__':
    keyword = '科技'
    main(keyword)

这段代码实现了一个简单的深度爬虫,它首先获取新闻列表页面的HTML内容,然后解析提取新闻标题和URL,筛选含有指定关键词的新闻,并将新闻的详情页URL交给一个新的函数来获取新闻详情。新闻详情被获取后,保存到CSV文件中。为了避免被目标网站封禁,爬虫在请求新的URL之前引入随机的等待时间。

2024-08-16



import requests
from bs4 import BeautifulSoup
 
def crawl_google(query, num_results=10):
    base_url = "https://www.google.com/search?q={query}&num={num}"
    params = {
        "query": query.replace(' ', '+'),
        "num": num_results
    }
    url = base_url.format(**params)
    headers = {
        "User-Agent": "Mozilla/5.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    }
    response = requests.get(url, headers=headers)
    return response.text
 
def crawl_bing(query, num_results=10):
    base_url = "https://www.bing.com/search?q={query}&count={num}"
    params = {
        "query": query.replace(' ', '+'),
        "num": num_results
    }
    url = base_url.format(**params)
    headers = {
        "User-Agent": "Mozilla/5.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    }
    response = requests.get(url, headers=headers)
    return response.text
 
def parse_results(html_content, engine='Google'):
    soup = BeautifulSoup(html_content, 'html.parser')
    results = soup.find_all('div', class_='r') if engine == 'Google' else soup.find_all('li', class_='b_algo')
    parsed_results = []
    for result in results:
        link = result.find('a')
        if link:
            title = link.text
            href = link['href']
            parsed_results.append({'title': title, 'link': href})
    return parsed_results
 
# 使用示例
google_results = parse_results(crawl_google('Python'), engine='Google')
bing_results = parse_results(crawl_bing('Python'), engine='Bing')
 
print("Google Results:")
for result in google_results:
    print(f"Title: {result['title']}, Link: {result['link']}")
 
print("\nBing Results:")
for result in bing_results:
    print(f"Title: {result['title']}, Link: {result['link']}")

这段代码定义了两个函数crawl_googlecrawl_bing来分别爬取Google和Bing的搜索结果,然后定义了一个parse_results函数来解析返回的HTML内容,提取出搜索结果的标题和链接。最后,我们使用这些函数来爬取"Python"作为关键词的搜索结果,并打印出来。这个例子展示了如何使用Python进行基本的网络爬虫,并且说明了如何处理动态内容和反爬虫策略。

2024-08-16



import requests
from bs4 import BeautifulSoup
 
# 定义一个简单的函数来获取网页内容
def get_html(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return None
    except requests.RequestException:
        return None
 
# 定义一个函数来解析网页并提取所需信息
def parse_html(html):
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们要提取的信息是标题
    title = soup.find('title')
    return title.text if title else None
 
# 使用示例
url = 'https://www.example.com'
html = get_html(url)
if html:
    parsed_title = parse_html(html)
    print(f"The title of the webpage is: {parsed_title}")
else:
    print("Failed to retrieve the webpage content.")

这段代码展示了如何使用requests库获取网页内容,并使用BeautifulSoup进行解析,提取特定的网页信息。代码简洁,注重实用性,可以作为编写Web爬虫的基础教程。

2024-08-16



using System;
using System.Net;
using System.IO;
 
class Program
{
    static void Main()
    {
        // 目标网页URL
        string url = "http://example.com";
 
        // 使用WebClient下载网页内容
        using (WebClient webClient = new WebClient())
        {
            try
            {
                // 下载网页
                string downloadedString = webClient.DownloadString(url);
 
                // 打印下载的内容
                Console.WriteLine(downloadedString);
            }
            catch (WebException ex)
            {
                // 处理可能发生的异常,例如网络错误
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

这段代码使用C#的WebClient类来下载网页内容。与Python中的requests库相比,.NET框架的WebClient提供了更为简洁和直观的API。虽然缺少一些高级功能,如cookie处理或者请求头的设置,但对于简单的网页内容抓取来说,WebClient是一个很好的起点。

2024-08-16

由于原始代码已经是一个完整的爬虫示例,我们可以提供一个简化的代码实例来说明如何使用Python爬取太平洋汽车网站的车型信息。




import requests
from bs4 import BeautifulSoup
import pandas as pd
 
# 设置请求头,模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
 
def get_car_models(url):
    # 发送GET请求
    response = requests.get(url, headers=headers)
    # 解析网页
    soup = BeautifulSoup(response.text, 'lxml')
    # 提取车型信息
    car_models = soup.find_all('div', class_='car-brand-list')
    return car_models
 
def parse_car_models(car_models):
    results = []
    for model in car_models:
        # 提取车型名称和链接
        name = model.find('a').text
        link = model.find('a')['href']
        results.append({'name': name, 'link': link})
    return results
 
def save_to_csv(data, filename):
    df = pd.DataFrame(data)
    df.to_csv(filename, index=False)
 
# 主函数
def main():
    base_url = 'http://www.pconline.com.cn/car/'
    car_models = get_car_models(base_url)
    parsed_data = parse_car_models(car_models)
    save_to_csv(parsed_data, 'car_models.csv')
 
if __name__ == '__main__':
    main()

这段代码首先定义了请求头,用于模拟浏览器访问网站。get_car_models 函数用于发送请求并获取网页内容,parse_car_models 函数用于解析网页并提取车型信息,最后将信息保存到CSV文件中。

注意:由于太平洋汽车网可能会更新其网站结构或实施反爬机制,因此上述代码可能无法在未来一定时间内正常工作。此外,在实际应用中应遵守网站的爬虫政策,避免对网站服务器造成过大压力,并确保爬取的数据仅用于合法目的。

2024-08-16

由于提出的查询涉及到的内容较多,我将提供一个简化版的购房比价系统的Python爬虫示例。这个示例将使用BeautifulSoup库来解析HTML页面,并使用requests库来发送HTTP请求。




import requests
from bs4 import BeautifulSoup
 
def fetch_housing_data(url):
    """
    发送HTTP请求,获取房源数据
    """
    response = requests.get(url)
    if response.status_code == 200:
        return response.text
    else:
        return None
 
def parse_data(html_content):
    """
    解析HTML内容,提取房源信息
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    # 假设我们要提取的房源信息在<div id="house-info"></div>中
    house_info = soup.find('div', {'id': 'house-info'})
    return {
        'price': house_info.find('span', {'class': 'price'}).text,
        'address': house_info.find('span', {'class': 'address'}).text
        # 根据实际情况提取更多信息
    }
 
def main():
    url = 'http://example.com/housing'  # 房源页面的URL
    html_content = fetch_housing_data(url)
    if html_content:
        housing_data = parse_data(html_content)
        print(housing_data)
    else:
        print('Failed to fetch housing data')
 
if __name__ == '__main__':
    main()

这个简单的Python脚本展示了如何使用requests和BeautifulSoup库来抓取一个假设的房源页面的数据。在实际应用中,你需要根据目标网站的HTML结构来调整解析代码。

注意:爬虫通常遵循“Robots.txt”协议,确保你有权限抓取目标网站的数据,并且不会给服务器带来过大压力。