【问题标题】:Unable to get some tabular content available in page source from a webpage using requests无法使用请求从网页获取页面源中可用的某些表格内容
【发布时间】:2020-11-09 10:46:29
【问题描述】:

我正在尝试从webpage 中抓取表格内容。问题是当我在脚本的标题中使用来自浏览器的硬编码 cookie 时,我可以在控制台中看到表格内容,否则当我摆脱 cookie 时,我会得到 200 响应而没有所需的内容。当我在这里粘贴代码时,cookie 可能已经过期了。

import requests
from bs4 import BeautifulSoup

link = 'https://www.health.gov.il/Subjects/KidsAndMatures/child_development/Pages/ADHD_experts.aspx'

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
    "Cookie":'ASP.NET_SessionId=hsqyvzg5jgkzfvzadzsyxdwx; p_hosting=!+bizF/4qwD7oEFze0NvCZLoPxuY/qnj9vRDa16ox8qkWDZTqjX1X9ZUoroByq7ynIZpFpUltU2jMCtk=; _ga=GA1.3.2020672306.1604911293; _gid=GA1.3.1145592749.1604911293; _hjTLDTest=1; _hjid=b62d7912-acfd-4ded-8a37-ae8b333fec04; WSS_FullScreenMode=false; _hjIncludedInPageviewSample=1; BotMitigationCookie_14016509088757896949="210109001604917723jho9/3TYoZILQoHOaZvAPwJt1Q8="; _gat_UA-72144815-4=1'
}

r = requests.get(link,headers=headers)
print(r.status_code)
soup = BeautifulSoup(r.text,"lxml")
print(soup.select_one('table:has(> caption.resultsSummaryPhones)'))

如何在不使用硬编码 cookie 的情况下使用请求获取表格内容?

【问题讨论】:

  • 能否请您添加上述网址的替代网址,其中网站内容为英文
  • 对不起@Vin,这是我唯一的链接。我正在尝试获得具有所需内容的响应。其余的我可以自己处理。

标签: python python-3.x web-scraping python-requests


【解决方案1】:

如果您不想使用硬编码的 cookie,您可能需要考虑在 headless 模式下使用 selenium 和 webdriver。

例如:

import time

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

driver.get('https://www.health.gov.il/Subjects/KidsAndMatures/child_development/Pages/ADHD_experts.aspx')
time.sleep(1)

soup = BeautifulSoup(driver.page_source, "html.parser").select_one('table:has(> caption.resultsSummaryPhones)')

phone_numbers = [
    n.getText(strip=True) for n
    in soup.find_all("td", {"class": "phoneBookListWorkPhone"})
    if n.getText(strip=True)
]

print(phone_numbers)

输出:

['02-5630147', '08-9330328', '03-6287200', '08-9703940', '08-8505515', '02-6413026', '04-6727000', '03-6302211', '04-8377717', '02-9939555       02-5887300', '04-9551155', '074-7034622']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 2020-02-14
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多