Python爬虫实战: 从ite-expo.ru网站提取展商数据

本文将教你如何使用Python编写一个网络爬虫,从 https://catalogue.ite-expo.ru/en-GB/exhibitorlist.aspx?project_id=489 爬取展商列表数据,包括公司名称、电话号码和网站地址。

以下是完整的Python代码:

import requests
from bs4 import BeautifulSoup

url = 'https://catalogue.ite-expo.ru/en-GB/exhibitorlist.aspx?project_id=489'
response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'id': 'exhibitorlist_tbl'})

for row in table.find_all('tr')[1:]:
    columns = row.find_all('td')
    name = columns[0].text.strip()
    phone = columns[2].text.strip()
    website = columns[3].find('a')['href'] if columns[3].find('a') else ''

    print(f'{name}: {phone} {website}')

代码解析:

  1. 导入库: 首先,我们导入 requests 库用于发送HTTP请求获取网页内容,以及 BeautifulSoup 库用于解析HTML结构。
  2. 发送请求: 使用 requests.get(url) 获取指定URL的网页内容,并存储在 response 对象中。
  3. 解析HTML: 使用 BeautifulSoup(response.text, 'html.parser') 将HTML代码解析成 BeautifulSoup 对象,方便后续提取数据。
  4. 定位表格: 使用 soup.find('table', {'id': 'exhibitorlist_tbl'}) 找到包含展商信息的表格。
  5. 遍历表格行: 使用 table.find_all('tr')[1:] 获取表格中所有数据行 (跳过表头)。
  6. 提取数据: 对于每一行,使用 row.find_all('td') 获取所有列,并分别提取公司名称、电话号码和网站地址。
  7. 处理缺失数据: 由于某些展商可能没有提供网站信息,我们使用 if columns[3].find('a') else '' 来判断是否存在链接,避免程序报错。
  8. 输出结果: 最后,使用 print(f'{name}: {phone} {website}') 将提取到的数据打印输出。

总结:

通过这段代码,你可以快速从 ite-expo.ru 网站上抓取展商数据。 这只是一个简单的示例,你可以根据自己的需求修改代码,例如将数据保存到CSV文件或数据库中。

Python爬虫实战: 爬取ite-expo.ru展商数据(附代码)

原文地址: https://www.cveoy.top/t/topic/jzKw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录