如何从包含循环的函数中抓取数据

How can I scrape data from a function which includes loops

我正在学习网络抓取(使用 Python 和 Beautiful Soup),我遇到了一个关于如何在包含循环的函数中抓取数据的问题。我要获取的数据是在 if,else 语句的条件下,如下所示。(下面的页面源)

我要报废“密码:h7s6sh

**<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password',' ');
while (testV < 3) {
if (!pass1) 
history.go(-1);
if (pass1.toLowerCase() == "ratedr") 
{
  alert('You Got it Right!');
  document.write("<center><h1>Username : hellomrxyz@gmail.com<p>Password :  h7s6sh</p></h1><p>NOTE : Visit daily Everyday</p><p><h1>Thank You!</h1></p></center>");break;
   } 
 testV+=1;
 var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password');
}
if (pass1.toLowerCase()!="password" & testV ==3) 
history.go(-1);
return " ";
} 
</SCRIPT>**

这是我正在尝试的脚本

>>> script_mim.text

u'\nfunction passWord() {\nvar testV = 1;\nvar pass1 = prompt(\'Please Enter Your Password\',\' \');\nwhile (testV < 3) {\nif (!pass1) \nhistory.go(-1);\nif (pass1.toLowerCase() == "ratedr") {\nalert(\'You Got it Right!\');\ndocument.write("<center><h1>Username : hellomrxyz@gmail.com<p>Password : h7s6sh</p></h1><p>NOTE : Visit daily Everyday</p><p><h1>Thank You!</h1></p></center>");\nbreak;\n} \ntestV+=1;\nvar pass1 = \nprompt(\'Access Denied - Password enter code hereIncorrect, Please Try Again.\',\'Password\');\n}\nif (pass1.toLowerCase()!="password" & testV ==3) \nhistory.go(-1);\nreturn " ";\n} \n\n'

>>> script_mim.find_all('p')

[]

为什么没有显示任何内容?我使用的是 python 3.x 的最新版本。你能告诉我我做错了什么,并提供解决方案吗?

Beautiful soup 只会理解并尝试解析 标签 而不是这些标签中的数据。由于 <script> 标记的提取内容将是一个 unicode 字符串,因此您无法解析结果。因此,您必须对结果执行字符串操作才能获得输出。您可以找到 <p></p> 的索引,并可以使用列表理解提取该标签并使用漂亮的汤重新解析它以获得输出 (方法 1) 或您可以直接对结果进行字符串操作以获得输出 (方法 2).

  1. 如果你重新解析由字符串提取的 <p></p> 标签 使用 BeautifulSoup 进行操作,那么您的代码将是

    soup=BeautifulSoup(script_mim.text[272:script_mim.text.find('</h1>')],"html.parser") #reinitialize beautifulsoup by extarcting <p> tag
    soup.find("p").get_text() #this will give you desired output.
    
  2. 如果通过字符串操作解析数据获取密码 您的代码将是

    script_mim.text[script_mim.text.find('<p>')+3:script_mim.text.find('</h1>')] 
    

我会推荐方法 2,因为与方法 1 相比,字符串操作的成本较低。