python - 如何在 Python 中抓取网页
问题描述
我想第一次做网页抓取一些用 JS 创建的网站。但我不知道如何在开发人员工具上找到表格。这是我的网站:https ://www.money.pl/gielda/gpw/akcje/
我的代码:
import requests
from bs4 import BeautifulSoup as soup
my_url = "https://www.money.pl/gielda/gpw/akcje/"
headers = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36")
page = requests.get(my_url, headers=headers, timeout=10)
page_soup = soup(page.text, 'lxml')
解决方案
尝试这个:
import csv
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
page = requests.get("https://money.pl/gielda/gpw/akcje/")
soup = BeautifulSoup(
page.content, "html.parser",
).find_all("div", class_="rt-tr-group")
akcje_gpw = [
[
i.getText(strip=True) for i in div.find("div") if i.getText()
] for div in soup
]
columns = [
"Walor", "Kurs PLN", "Zmiana (%)", "Otwarcie",
"Min", "Max", "Obrót (szt.)", "Obrót (PLN)",
"Czas aktualizacji",
]
print(tabulate(akcje_gpw[:10], headers=columns))
with open("akcje_tabela.csv", "w") as f:
w = csv.writer(f)
w.writerow(columns)
w.writerows(akcje_gpw)
输出:
Walor Kurs PLN Zmiana (%) Otwarcie Min Max Obrót (szt.) Obrót (PLN) Czas aktualizacji
---------------------------- ---------- ------------ ---------- ------ ------ -------------- ------------- -------------------
11 bit studios SA 485,00 -2,61 492,00 485,00 499,50 4 512 2 213 838 2021-01-29
3R Games SA 1,03 -0,96 1,07 1,03 1,07 11 757 12 482 2021-01-29
4Fun Media SA 6,48 +2,86 6,76 6,30 6,76 6 618 42 777 2021-01-29
AB SA 31,40 +0,64 31,10 31,10 31,80 10 633 335 017 2021-01-29
AC SA 35,00 0,00 35,50 34,80 35,50 3 080 107 836 2021-01-29
Action SA w restrukturyzacji 5,92 -0,67 6,06 5,84 6,06 14 456 86 121 2021-01-29
Adiuvo Investments SA 4,90 +4,26 4,85 4,83 4,96 8 865 43 344 2021-01-29
Agora SA 6,84 -0,87 6,86 6,84 6,94 13 001 89 663 2021-01-29
Agroton Plc 7,16 +0,85 7,10 6,80 7,18 31 773 223 314 2021-01-29
Ailleron SA 11,60 -0,85 11,55 11,30 11,80 7 487 86 225 2021-01-29
---------------------------- ------ ----- ------ ------ ------ ------ --------- ----------
这是.csv
文件中的内容:
推荐阅读
- sql - 如何创建一个触发器来计算从一个表到另一个表的具有匹配 id 的字段的总和?
- html - 虽然 #navbar 宽度是 100% 并且还设置了 box-sizing ,但 navbar 比右侧的 body 宽一点,为什么?#navbar 固定并且宽度是 100%
- python - 必需的位置参数,“类型错误:缺少自我参数”
- python-3.x - 不添加所有不在字典值中的元素
- python - Python Pandas 根据条件更改值
- c# - Webdriver 管理器和 c#
- python - 你如何在 django 中渲染图像?
- python - 在 python 中绘制间隔时无法将 IntervalIndex 转换为 dtype int32 错误
- java - 使用适当权限对 Microsoft Graph 进行 API 调用时出现 403 错误
- mysql - MySQL触发器比较OLD和NEW中的所有列